计算字符串中的字母频率(Python)

问题描述 投票:0回答:7

我试图计算一个单词的每个字母的出现次数

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

python frequency-analysis
7个回答
14
投票
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])的当前代码执行一个条件,尽管这会慢一些。


4
投票
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'))

2
投票

正如@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}

1
投票

无lib的简单易用的解决方案。

string=input()
f={}
for i in string:
  f[i]=f.get(i,0)+1
print(f)

这是get()https://docs.quantifiedcode.com/python-anti-patterns/correctness/not_using_get_to_return_a_default_value_from_a_dictionary.html的链接


0
投票

跟进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。


0
投票

对于将来的参考:当你有一个包含你想要的所有单词的列表时,让我们说wordlistit非常简单

for numbers in range(len(wordlist)):
    if wordlist[numbers][0] == 'a':
        print(wordlist[numbers])

0
投票
s=input()
t=s.lower()

for i in range(len(s)):
    b=t.count(t[i])
    print("{} -- {}".format(s[i],b))
© www.soinside.com 2019 - 2024. All rights reserved.