计算长字符串中的字母(仅字母)(python 2.72)
我需要编写一个接收长字符串并放入字典的函数 每个字母,以及它在字符串中的出现频率。 我写了下一个函数,但问题是它没有忽略空格、数字等。 我被要求使用函数 symbol in string.ascii_lowercase
,但我不知道该怎么做。 这是我的代码:
def calc_freq(txt):
dic={}
for letter in range(len(txt)):
if dic.has_key(txt[letter])==True:
dic[txt[letter]] += 1
else:
dic[txt[letter]] = 1
return dic
感谢您的帮助。
i need to write a function which receives a long string, and puts into a dictionary
each letter, and it's it's appearance frequency in the string.
iv'e written the next function, but the problem it doesn't ignore whitespaces, numbers etc..
iv'e been asked to use the function symbol in string.ascii_lowercase
, but iv'e no idea how to do it.
this is my code:
def calc_freq(txt):
dic={}
for letter in range(len(txt)):
if dic.has_key(txt[letter])==True:
dic[txt[letter]] += 1
else:
dic[txt[letter]] = 1
return dic
thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只是为了好玩:
just for fun:
这将创建一个字符及其计数的字典,并且仅当它们位于
string.ascii_lowercase
列表中时才包含它们。以下是如何在代码中使用它:
您只需在将字母添加到字典或增加其计数之前添加一个 if 语句。
我还删除了
letter in range(txt)
和txt[letter]
,您可以直接在 python 中访问每个字符,因为字符串是一个iterable
code> 并且可以像列表一样对待。this will create a dictionary of the charactors and their counts, and only include them if they are in the
string.ascii_lowercase
list.Here is how to use it in your code:
you just needed to add an if statment before you add the letter to the dictionary or increase its count.
I also removed the
letter in range(txt)
andtxt[letter]
, you can access each charactor directly in python, because a string is aniterable
and can be treated similar to a list.