【问题标题】:Search values in a list from a file从文件的列表中搜索值
【发布时间】:2019-01-17 18:34:30
【问题描述】:

文本文件上的单词搜索,我需要检查一个单词是否出现在大量文件中。使用我的程序工作的唯一单词,我想使用列表扩展到单词列表,但是我无法使其工作。

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 中是否存在的概念问题 有人可以建议吗? )

【问题讨论】:

  • 您发布的代码因各种缺少符号定义和缩进错误而无法运行。输出文件(除其他外)对您的问题是多余的。最重要的是,您应该包括一个使用目标词列表的简单尝试——这不会出现在您的代码或描述中的任何地方。

标签: python arrays arraylist


【解决方案1】:

为此,您需要使用正则表达式,并且可以使用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()

【讨论】:

  • 使用正则表达式是否可以打印找到了哪个单词以及该单词出现的第 # 行?
  • 我用一个示例更新了答案,该示例将打印文件名、行、位置和单词。
  • 嗨!套装是干什么用的?另外,忽略大小写将所有内容都放在大写字母中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多