gpt4 book ai didi

python字典函数,文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:46 28 4
gpt4 key购买 nike

我想定义一个函数 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()

关于python字典函数,文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20107509/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com