我创建了一个字母表的字典,其值从0开始,并根据单词文件增加一定数量。我硬编码了最初的字典,并希望它保持字母顺序,但实际上并没有。我希望它以字母顺序返回字典,基本上与最初的字典保持相同。
如何保持其顺序?
from wordData import*
def letterFreq(words):
totalLetters = 0
letterDict = {'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,
'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0}
for word in words:
totalLetters += totalOccurences(word,words)*len(word)
for char in range(0,len(word)):
for letter in letterDict:
if letter == word[char]:
for year in words[word]:
letterDict[letter] += year.count
for letters in letterDict:
letterDict[letters] = float(letterDict[letters] / totalLetters)
print(letterDict)
return letterDict
def main():
filename = input("Enter filename: ")
words = readWordFile(filename)
letterFreq(words)
if __name__ == '__main__':
main()
for year in words[word]: letterDict[letter] += year.count
这段代码非常令人困惑。你能详细解释一下这段代码的作用吗?另外,float(letterDict[letters] / totalLetters)
可能不会像你想象的那样工作。 - jpmc26