adsqw qwe
adsqw qwe

Reputation: 49

python using search engine to find text in text file

I have lots of text files in a directory.Then i will ask a keyword from the user.If the user enters for eg: 'hello'
Then,it has to search the entire text file of all the directories present in the text file and then search and return the line of the text file ,having the high priority of word hello.

Eg:

input: helloworld

output:

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

Give me some ideas on how to deal with such problems!

Upvotes: 0

Views: 1479

Answers (2)

Yanuar Kusnadi
Yanuar Kusnadi

Reputation: 243

Using glob as alternative, you can filter for specific file name, extension or all file in directory.

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

Upvotes: 3

Amadan
Amadan

Reputation: 198378

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:
    ....

This will find all mentions of "hello" in current directory or below. man grep for details on options. Be aware you will need to quote any special characters; if you're looking for simple words, this is not necessary, but if you're handling user input, you need to care about it.

Upvotes: 1

Related Questions