python使用搜索引擎在文本fi中查找文本

2024-07-02 13:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多文本文件目录。那么我将从用户。如果用户输入例如:“hello”
然后,它必须搜索文本文件中所有目录的整个文本文件,然后搜索并返回文本文件的行,具有wordhello的高优先级。在

例如:

input: helloworld

输出:

^{pr2}$

给我一些如何处理这些问题的想法!在


Tags: 用户目录helloinputhelloworld文本文件pr2wordhello
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:
    ....

这将找到所有提到“你好”在当前目录或下面。man grep获取有关选项的详细信息。请注意,您将需要引用任何特殊字符;如果您要查找简单的单词,这是不必要的,但是如果您处理的是用户输入,则需要关心它。在

使用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

相关问题 更多 >