问题描述
我最近才开始学习Python。我想计算列表中每个字符的频率。但是,我的代码仅适用于列表中的第一个元素。
我的代码:
import sys
n = [str(s) for s in sys.argv[1].split()]
def countLetter(n):
frequencyLetter = {}
for word in n:
for letter in word:
keys = frequencyLetter.keys()
if letter in keys:
frequencyLetter[letter] += 1
else:
frequencyLetter[letter] = 1
return frequencyLetter
print(countLetter(n))
结果:
C:\Users\john\pythonlearn\testing> main.py hello,there
{'h': 1,'e': 1,'l': 2,'o': 1,',': 1}
应该计算“ hello”和“ there”的字符频率。我不知道为什么输出中有一个---->',':1
解决方法
我在这里看到两个问题:
- 您正在错误地解析参数列表。
- 无需手动增加计数器。
Counter
中的collections
类在这里可以很好地工作:
import sys
from collections import Counter
arglist = sys.argv[1:] # exclude filename
def count_letters(args):
# Results will be stored in a dict
res = {}
for word in args:
x = Counter(word)
res.update(x)
return res
res = count_letters(arglist)
print(res)
此外,鉴于您似乎很想在参数中检查逗号(即使您可以通过用空格将它们分隔开来轻松避免这种情况),也可以在添加它们之前先将其删除到Counter
对象:
def count_letters(args):
# Results will be stored in a dict
res = {}
for word in args:
# If a comma is found,strip it out
if "," in word:
word = word.replace(",","")
x = Counter(word)
res.update(x)
return res
使用python parse.py hello there
或python parse.py hello,there
调用脚本将得到以下相同结果:
{'h': 1,'e': 2,'l': 2,'o': 1,'t': 1,'r': 1}