问题描述
我正在编写一个程序来根据用户输入来计算字母的频率,直到“!”为止。被介绍了。以下是我的程序:
list1=[]
character = ""
while character != '!' :
character = input()
list1.append(character)
result=[]
for alphabet in ['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'] :
if list1.count(alphabet) > 0:
result.append(alphabet)
result.append(list1.count(alphabet))
print(result)
但是,显然,我应该已经计算过频率,直到在输入中插入新字符为止。 例如,如果输入为(aabc),则我的程序应将两个“ a”相加,然后移至“ b”。
无论如何,在继续使用新字母之前,我是否需要修改循环以计数频率?
解决方法
d = {}
while True:
temp = input().strip()
if temp == '!':
break
if temp.islower() is False:
print("Invalid character")
continue
if temp not in d:
d[temp] = 1
else:
d[temp] += 1
我用过字典
d
将包含执行后的结果。
import string
alpha = string.printable[10:36]
# [a-z]
# return a dictionary consists of keys of 26 alphabets and values of frequency
def detect(string):
di = {}
for k in alpha:
di[k] = string.count(k)
return di
text = ""
print('Please input the text,end with a exclamation mark !')
while text.count('!') == 0:
text += input()
# get rid of any after exclamation mark
main_text = text.split('!')[0]
print('result is: ' + str(detect(main_text)))
如果要包含大写字母:
import string
alpha = string.printable[10:62]
# [a-Z]
# return a dictionary consists of keys of 26 alphabets and values of frequency
def detect(string):
di = {}
for k in alpha:
di[k] = string.count(k)
return di
text = ""
print('Please input the text,end with a exclamation mark !')
while text.count('!') == 0:
text += input()
# get rid of any after exclamation mark
main_text = text.split('!')[0]
print('result is: ' + str(detect(main_text)))
如果您不想处理string
模块,并且只要能识别utf-8字符,就计算每个输入的频率:
def detect(string):
di = {}
for k in string:
di[k] = string.count(k)
return di
text = ""
print('Please input the text,end with a exclamation mark !')
while text.count('!') == 0:
text += input()
# get rid of any after exclamation mark
main_text = text.split('!')[0]
print('result is: ' + str(detect(main_text)))
最后,如果您只想计算低26个字母:
import string
alpha = string.printable[10:36]
# [a-z]
def detect(info):
di = {}
for k in info:
if k in alpha:
di[k] = info.count(k)
return di
text = ""
print('Please input the text,end with a exclamation mark !')
while text.count('!') == 0:
text += input()
# get rid of any after exclamation mark
main_text = text.split('!')[0]
print('result is: ' + str(detect(main_text)))