为了完成我的硕士论文,我下载了大量与财务相关的文件。我的目标是找到一组特定的词(“第 11 章”)来标记所有经历过债务重组过程的公司。 问题是我有超过 120 万个小文件,这使得搜索效率非常低。现在我写了非常基本的代码,我达到了每 40-50 秒 1000 个文档的速度。我想知道是否有一些特定的库或方法(甚至编程语言)可以更快地搜索。这是我目前使用的功能
def get_items(m):
word = "chapter 11"
f = open(m, encoding='utf8')
document = f.read()
f.close()
return (word in document.lower())
# apply the function to the list of names:
l_v1 = list(map(get_items,filenames))
文件的大小在 5 到 4000 KB 之间
最佳答案
试试 Unix 工具,grep
。
如果文件很少,你可以这样做:
grep -i "chapter 11" file1 file2 ...
或者,
grep -i "chapter 11" file*.txt
如果文件很多,可以结合grep
和find
:
find . -type f | xargs grep -i "chapter 11"
另一个强大的工具是 ack
(用 Perl 编写)——参见 https://beyondgrep.com/ .
关于python - 在多个文件中搜索单词的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74121671/