我试图计算一个单词的每个字母的出现次数
word = input("Enter a word")
Alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in range(0,26):
print(word.count(Alphabet[i]))
这当前输出每个字母出现的次数,包括不出现的次数。
如何垂直列出字母和频率,例如:
字=“你好”
H 1
E 1
L 2
1
from collections import Counter
counts=Counter(word) # Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
for i in word:
print(i,counts[i])
尝试使用Counter
,它将创建一个包含集合中所有项目频率的字典。
否则,只有当print
大于0时,你才可以对word.count(Alphabet[i])
的当前代码执行一个条件,尽管这会慢一些。
def char_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
print(char_frequency('google.com'))
正如@Pythonista所说,这是collections.Counter
的工作:
from collections import Counter
print(Counter('cats on wheels'))
这打印:
{'s': 2, ' ': 2, 'e': 2, 't': 1, 'n': 1, 'l': 1, 'a': 1, 'c': 1, 'w': 1, 'h': 1, 'o': 1}
无lib的简单易用的解决方案。
string=input()
f={}
for i in string:
f[i]=f.get(i,0)+1
print(f)
跟进LMc所说的,您的代码已经非常接近功能,您只需要对结果集进行后处理以删除“不感兴趣”的输出。这是使代码工作的一种方法:
#!/usr/bin/env python
word = raw_input("Enter a word: ")
Alphabet = [
'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'
]
hits = [
(Alphabet[i], word.count(Alphabet[i]))
for i in range(len(Alphabet))
if word.count(Alphabet[i])
]
for letter, frequency in hits:
print letter.upper(), frequency
但使用collections.Counter
的解决方案更优雅/ Pythonic。
对于将来的参考:当你有一个包含你想要的所有单词的列表时,让我们说
wordlist
it非常简单
for numbers in range(len(wordlist)):
if wordlist[numbers][0] == 'a':
print(wordlist[numbers])
s=input()
t=s.lower()
for i in range(len(s)):
b=t.count(t[i])
print("{} -- {}".format(s[i],b))