使用python中的字典计算每个字符的频率



我的程序接受用户的字符串作为输入,并使用字典计算每个字符的频率。输入:

Python programming is fun

预期输出:

{'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 2, 's': 1, 'f': 1, 'u': 1}

我的代码:

string = input().lower()
dicx = {}
count = 0
for i in string:
dicx['i'] = ''
print(dicx)

使用集合。计数器

dicx = collections.Counter(string.lower())

您可以迭代字符串并相应地更新字典,而且不需要任何计数变量。

test_str = input().lower()
dicx = {} 

for i in test_str: 
if i in dicx: 
dicx[i] += 1
else: 
dicx[i] = 1
print(dicx)

函数将输入作为字符串,对字符进行计数并将其存储在字典中

from typing import Dict

char_dict = {} #type: Dict[str, int]

def char_count(string: str) -> dict:
new_string = string.lower()
for c in new_string:
if c in char_dict:
char_dict[c] += 1
else:
char_dict[c] = 1
return char_dict

if __name__ == "__main__":
UserString = input("Enter Input String: ")
CharCount = char_count(UserString)
print("Characters Count: ", CharCount)

示例:

Enter Input String: Python programming is fun
Characters Count:  {'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, ' ': 3, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 2, 's': 1, 'f': 1, 'u': 1}

方法1:对于

symbols = {}
for s in inp_str.lower():
if s in symbols:
symbols[s] += 1
else:
symbols.update({s: 1})
print(symbols)

方式2:defaultdict

symbols = defaultdict(int)
for s in inp_str.lower():
symbols[s] += 1
print(symbols)

方法3:计数器

symbols = Counter(inp_str.lower())
print(symbols)
def charCounter(string):
empty = {}
for i in string.lower():
if i in empty.keys():
empty[i] += 1
else:
empty[i] = 1
return empty
print(charCounter("Oh, it is python"))
d = {}
test_str = input().lower()
for x in test_str:
d[x] = d.get(x,0) + 1
print(d)

像这个更优雅

最新更新