【问题标题】:python using search engine to find text in text filepython使用搜索引擎在文本文件中查找文本
【发布时间】:2017-01-11 13:52:07
【问题描述】:

我在一个目录中有很多文本文件。然后我会向用户询问一个关键字。如果用户输入例如:'hello'
然后,它必须搜索文本文件中存在的所有目录的整个文本文件,然后搜索并返回文本文件的行,具有单词hello的高优先级。

例如:

input: helloworld

输出:

filename: abcd.txt
line : this world is a good world saying hello

给我一​​些关于如何处理这些问题的想法!

【问题讨论】:

  • 委托给grep,会比你在Python中做的任何事情都快。
  • 根据你有多少文件,它们有多大等等,你可能想看看 Whoosh,一个用纯 Python 编写的全文索引包
  • @Amadan 你能解释一下或者给我一些链接吗?
  • @duhaime 是的,我听到了,但我没有在网上看到与我的问题相关的示例。你能给我一些链接吗?
  • @duhaime:这是您在非索引数据上获得的最快速度,只要您注意正确的 regexp/shell 转义(这在后面很痛苦)。如果您有大量数据,您仍然可以使用Popen 长路(使用管道)而不是check_output 快捷方式来完成。也就是说,任何索引数据而不是进行原始搜索的方法都将比我编写的 hack 更快。 :)

标签: python search-engine


【解决方案1】:

使用 glob 作为替代,您可以过滤特定文件名、扩展名或目录中的所有文件。

>>> from glob import glob
>>> key = 'hello'
>>> for file in glob("e:\data\*.txt"):
    with open(file,'r') as f:
        line_no = 0
        for lines in f:
            line_no+=1
            if key.lower() in lines.lower():
                print "Found in " + file + "(" + str(line_no) + "): " + lines.rstrip()

Found in e:\data\data1.txt(1): Hello how are you
Found in e:\data\data2.txt(4): Searching for hello
Found in e:\data\data2.txt(6): 3 hello

【讨论】:

    【解决方案2】:
    import subprocess
    output = subprocess.check_output(["/usr/bin/env", "grep", "-nHr", "hello", "."])
    matches = (line.split(":", 2) for line in output.split("\n") if line != "")
    for [file, line, text] in matches:
        ....
    

    这将在当前目录或以下目录中找到所有提及“hello”的内容。 man grep 了解有关选项的详细信息。请注意,您需要引用任何特殊字符;如果您正在寻找简单的单词,这不是必需的,但如果您正在处理用户输入,则需要关注它。

    【讨论】:

      猜你喜欢
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      相关资源
      最近更新 更多