问题描述
我正在尝试找到一种方法来遍历文本文件并列出以查找字符频率。我知道我可以为此使用Count()。但是Count()提供了所有内容,包括空格和诸如此类。此外,它也不按字母顺序显示字符频率。我找到了一种方法,但确实有效。我稍后再解释。另外,当我尝试增加频率时,也会收到KeyError。我也会解释。
我不想把整个项目放在这里,所以我先解释一些东西。我有一个单独的列表,称为Alphabet_list,其中包含字母。有一个已经读完并转换为大写的文本文件,称为new_text。
字符频率代码:
for i in range(len(alphabet_list)):
for c in new_text:
if c == alphabet_list[i]:
count += 1
else:
count = 0
print(alphbet_list[i] + " " + str(count)
i += 1
输出
A 0
A 0
.
.
.
A 1
A 0
.
.
.
B 0
.
.
.
B 1
B 2
B 0
.
.
.
Z 0
P.S str(count)临时存在,是因为我想看看打印出来的样子,我需要将结果存储在字典中
我的输出将是这样,就像我说的那样,但并非如此。它会迭代,但是会迭代遍历每个字母并已经打印出结果,并且不会迭代整个文本文件,而只是打印最终结果。如果另一个字母彼此相邻,它将添加到结果中。 Ex(... bb ...)将会是B 1,B 2,如我的输出所示。出于某种原因,当我使用return时,它不起作用。它不返回任何内容,仅结束程序。
带有KeyError的第二代码:
- 我跳过了这个问题,因为我找不到答案,不想浪费时间,但遇到了另一个问题,哈哈*
for i in range(len(alphabet_list)):
for c in new_text:
if c == alphabet_list[i]:
count += 1
else:
count = 0
c_freq[alphabet_list[i]] == count
print(c_freq)
i += 1
这很简单,我得到了一个KeyError:'A'。 我尝试只做
i = 3 #just random number to test
count = 50
c_freq[alphabet_list[i]] == count
print(c_freq)
并且有效,所以我认为问题也与上面的问题有关(也许?)。无论如何,任何帮助都会很棒。谢谢!
很抱歉很长的问题,但我确实需要帮助。
解决方法
这应该可以帮助您:
lst = ['A','Z','H','A','B','N','Y','.',','Z'] #Initial list. Note: The list also includes characters such as commas and full stops.
alpha_dict = {}
for ch in lst:
if ch.isalpha(): #Checks if the character is an alphabet
if ch in alpha_dict.keys():
alpha_dict[ch] += 1 #If key already exists,value is incremented by 1
else:
alpha_dict[ch] = 1 #If key does not exist,a new key is created with value 1
print(alpha_dict)
输出:
{'A': 2,'Z': 2,'H': 2,'B': 1,'N': 1,'Y': 1}
由于您希望输出按字母顺序排序,因此请在代码中添加以下行:
key_list = list(alpha_dict.keys()) #Creates a list of all the keys in the dict
key_list.sort() #Sorts the list in alphabetical order
final_dict = {}
for key in key_list:
final_dict[key] = alpha_dict[key]
print(final_dict)
输出:
{'A': 2,'Y': 1,'Z': 2}
因此,这是最终代码:
lst = ['A','Z']
alpha_dict = {}
for ch in lst:
if ch.isalpha():
if ch in alpha_dict.keys():
alpha_dict[ch] += 1
else:
alpha_dict[ch] = 1
key_list = list(alpha_dict.keys())
key_list.sort()
final_dict = {}
for key in key_list:
final_dict[key] = alpha_dict[key]
print(final_dict)
输出:
{'A': 2,'Z': 2}