【发布时间】:2021-01-25 15:11:24
【问题描述】:
我是 python 新手;我正在寻找计算源频率。我有文件(来源在标记中),我想找到所有来源中显示的单词来计算。例如,显示来源的单词“beautiful”,结果单词“beautiful”在 5 个来源中。我已经有了python代码来查找一个单词,但是我需要从文件中查找所有单词,我应该如何更改代码??
from os import listdir
with open("C:/Users/elle/Desktop/Archivess/test/rez.txt", "w") as f:
for filename in listdir("C:/Users/elle/Desktop/Archivess/test/sources/books/"):
with open('C:/Users/elle/Desktop/Archivess/test/freqs/books/' + filename) as currentFile:
text = currentFile.read()
if ('beautiful' in text):
f.write('The word excist in the file ' + filename[:-4] + '\n')
else:
f.write('The word doen't excist in the file' + filename[:-4] + '\n')
感谢您的帮助,谢谢!
【问题讨论】:
-
在
f.write('The word doen't excist in the file' + filename[:-4] + '\n')中,您需要转义',例如doen\'t而不是don't -
如果您要对很多非常大的文件执行此操作,并且如果性能成为问题,您可能需要查看this answer 以获取性能改进的想法。
标签: python pandas xcode file frequency