python - 从文件的列表中搜索值
问题描述
在文本文件上进行单词搜索,我需要检查一个单词是否出现在大量文件中。使用我的程序工作的唯一单词,我想使用列表扩展到单词列表,但是我无法使其工作。
for name in files:
try:
with open(name,errors='ignore') as f:
found = "FALSE"
pos = 0
for line in f:
pos = pos + 1
if pattern_finder(line):
found = "TRUE"
break
output_file.write (ntpath.basename(f.name) +';' + found + ';' + str(pos)+ ';' + line )
except IOError as exc:
if exc.errno != errno.EISDIR:
print("No Files Found")
raise
output_file.close()
def pattern_finder (file_line):
for i in range(len(pattern_to_find)):
word = pattern_to_find[i]
if word in file_line:
return True
break
永远找不到该行中的“单词”,当然,如果我只是避免使用列表,它可以正常工作,即 word="WORD_IM_LOOKING" 我相信我对如何从列表中获取要使用的值有一个概念性问题该值是否存在于 list.index 中,有人可以建议吗?)
解决方案
为此,您需要使用正则表达式,并且可以使用str.join
管道字符和单词列表来编译正则表达式交替模式。例子:
import re
from pathlib import Path
def main():
search_words = ['words', 'one', 'two']
p = re.compile(r'|'.join(search_words), re.IGNORECASE|re.MULTILINE)
files_with_words = []
for file in Path().glob('*.txt'):
if p.search(file.read_text()):
files_with_words.append(file.name)
print(files_with_words)
if __name__ == '__main__':
main()
编辑:更新以显示找到的行号、位置和单词。
import re
from pathlib import Path
def main():
search_words = ['words', 'one', 'two']
p = re.compile(fr"\b({'|'.join(search_words)})\b", re.IGNORECASE)
files_with_words = set()
for file in Path().glob('*.txt'):
with open(file.name) as f:
for i, line in enumerate(f):
re_search_obj = p.search(line)
if re_search_obj:
print("file={}, line={}, pos={}, word={}".format(
file.name, i, re_search_obj.span(), re_search_obj.group()
))
if __name__ == '__main__':
main()
推荐阅读
- r - 使用 R 的流程图
- reactjs - 在 react-contenteditable 中渲染 JSX 元素
- java - 如何使反应时间在我的 while 循环中工作
- mysql - 合并2个数据库MySQL
- java - Proguard:无法读取 C:\Program Files\Java\jdk-15.0.1\lib\rt.jar(没有这样的文件或目录)
- c# - 即使底层数据类型重叠,我是否可以在这种情况下定义表关系以使级联删除流动?
- google-cloud-platform - Google Compute Engine 上的 E2 CPU 使用率随着时间的推移而上升
- json - 从 Linux 命令中的 json 样式输出中提取变量
- flutter - 带有线条而不是点颤动的轮播滑块
- c++ - 避免在 C++ 中破坏对象