gpt4 book ai didi

python - 唯一的单词作为每行一个单词保存到文本文件中

转载 作者:行者123 更新时间:2023-11-30 23:10:25 25 4
gpt4 key购买 nike

[使用Python 3.3.3]

我正在尝试分析文本文件,清理它们,打印唯一单词的数量,然后尝试将唯一单词列表保存到文本文件中,每行一个单词以及每个唯一单词出现的次数清理后的单词列表。所以我所做的是我获取了文本文件(哈珀总理的演讲),通过仅计算有效的字母字符和单个空格来清理它,然后我计算了唯一单词的数量,然后我需要制作一个保存的文本文件唯一单词的数量,每个唯一单词都在自己的行上,并且在该单词旁边,该单词在清理列表中出现的次数。这就是我所拥有的。

def uniqueFrequency(newWords):
'''Function returns a list of unique words with amount of occurances of that
word in the text file.'''
unique = sorted(set(newWords.split()))
for i in unique:
unique = str(unique) + i + " " + str(newWords.count(i)) + "\n"
return unique

def saveUniqueList(uniqueLines, filename):
'''Function saves result of uniqueFrequency into a text file.'''
outFile = open(filename, "w")
outFile.write(uniqueLines)
outFile.close

newWords 是文本文件的清理版本,只有单词和空格,没有其他内容。因此,我希望将 newWords 文件中的每个唯一单词保存到一个文本文件中,每行一个单词,并且在该单词旁边,列出该单词在 newWords 中出现的次数(不在唯一单词列表中,因为这样每个单词都会出现 1 次)。我的功能出了什么问题?谢谢!

最佳答案

unique = str(unique) + i + " " + str(newWords.count(i)) + "\n"

上面的行附加在现有集合的末尾 - “unique”,如果您使用其他变量名称(例如“var”),则应该正确返回。

def uniqueFrequency(newWords):
'''Function returns a list of unique words with amount of occurances of that
word in the text file.'''
var = "";
unique = sorted(set(newWords.split()))
for i in unique:
var = str(var) + i + " " + str(newWords.count(i)) + "\n"
return var

关于python - 唯一的单词作为每行一个单词保存到文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30690649/

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