因此,我不仅需要计算单词中字母的出现频率,还需要吐出未使用的字母。
#Dictionary and lists etc...
alphabetList = ["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"]
#Dictionary and lists etc...
def Checksums():
for i in alphabetList:
# Get everything ready to edit
character = i
myString = Phrase
myList = []
#DONE GATHERING RESOURCE
for i in myString:
myList.append(i)
myList = myList.sort()
print myList
count = 0
for i in myList:
if i == character:
count = count +1
else:
continue
print("There are ", count, " occurrences of ", character )
#input
Phrase = str(raw_input("Enter a Phrase: "))
Phrase = Phrase.lower()
# print (Phrase)
Phrase = Phrase.replace(" ", "")
# print Phrase
Checksums()
请原谅我对python的了解,语法与java不同,有时会令人沮丧
输入的示例可能是:aaA cC D并且返回将是
“字母“ a”出现了3次”“出现了字母'c'的'2'个出现”“只有1个'd'”“其余字母未使用”bË等等...
我觉得这可能与我不了解的语法/逻辑有关。例如,我尝试使用字母列表并循环浏览,但是我得到了
TypeError:'NoneType'对象不可迭代
用您的功能中的myList = myList.sort()
替换myList.sort()
。
使用Python的Counter和set确定缺少的键,结果为:
import string
from collections import Counter
def check(phrase):
phrase = phrase.lower().replace(" ", "")
phrase = Counter(phrase)
for counts in phrase.items():
print ("There were %s occurrences of the letter %s" % counts[::-1])
missingCharacter = set(string.ascii_lowercase) - set(phrase.keys())
print("The remaining letters are unused: %s" % ','.join(missingCharacter))
check('aaA cC D')
输出:
There were 3 occurrences of the letter a
There were 2 occurrences of the letter c
There were 1 occurrences of the letter d
The remaining letters are unused: b,e,g,f,i,h,k,j,m,l,o,n,q,p,s,r,u,t,w,v,y,x,z
一些简化代码的方法
首先,要计算字符串中每个字母的出现次数,请使用字典:
d = {};
for c in myString:
d[c] = (d[c]+1) if (c in d) else 1
然后打印每个字母的统计信息:
# used letters:
for k in d:
print("There are ", d[k], " occurrences of ", k)
#unused letters
for o in range(ord('a'),ord('z')):
k = chr(o)
if not (k in d):
print("No occurrence of ", k, " in string")
或合并:
for o in range(ord('a'),ord('z')):
k = chr(o)
if not (k in d):
print("No occurrence of ", k, " in string")
else:
print("There are ", d[k], " occurrences of ", k)
您可以尝试使用此
alphabetList = ["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"]
def occurence_counter(phrase):
unused_letters = ""
for alphabet in alphabetList:
count = phrase.count(alphabet)
if count > 1:
print("There are ", count, " occurrences of ", alphabet )
else:
unused_letters = unused_letters + alphabet
print("The remaining letters are unused" + unused_letters)
Phrase = str(input("Enter a Phrase: "))
Phrase = Phrase.lower()
occurence_counter(Phrase)
由于嵌套循环,请勿将所有的'i'用作变量