我想定义一个函数 scaryDict(),它接受一个参数(textfile)并返回 textfile 中的单词按字母顺序排列,基本上生成字典但不打印任何一个或两个字母的单词。
这是我目前所拥有的……不多,但我不知道下一步
def scaryDict(fineName):
inFile = open(fileName,'r')
lines = inFile.read()
line = lines.split()
myDict = {}
for word in inFile:
myDict[words] = []
#I am not sure what goes between the line above and below
for x in lines:
print(word, end='\n')
请您参考如下方法:
在 line = lines.split() 之前,您一切都很好。但是您的 for 循环必须遍历行数组,而不是 inFile。
for word in line:
if len(word) > 2: # Make sure to check the word length!
myDict[word] = 'something'
我不确定你想要字典做什么(也许得到字数?),但一旦你有了它,你就可以得到你添加到它的字,
allWords = myDict.keys() # so allWords is now a list of words
然后您可以对 allWords 进行排序,让它们按字母顺序排列。
allWords.sort()
