1.11M Members

find string in file

 
0
 

Hi friends !!

I'm neophite about python, my target is to create a programa that
find a specific string in text file.
How can do it?


Thanks
fel

 
1
 

The simplest way, but maybe not the most efficient for large files, is this:

# sample text for testing
# could come from a text file read like this:
"""
infile = open("my_text.txt","r")
text = infile.read()
infile.close()
"""

text = """\
My name is Fred Flintstone and I am a famous TV
star.  I have as much authority as the Pope, I
just don't have as many people who believe it.
"""

search = "Fred"
index = text.find(search)
print search, "found at index", index

"""
my ouput (index is zero based) -->
Fred found at index 11
"""

Note that find() only finds the first occurrence of the search word!

 
1
 

FWIW this will find all occurrences of a word in a string. Also note that if you are looking for "the" it will give a hit for "then". If you only want the word, you have to search with spaces added, " the " -assuming string.lower() and that punctuation is removed

found=the_string.find(word)
while found > -1:
     print word, "found at location", found
     found=the_string.find(word, found+1)
 
-1
 

I kinda have the sane problem, but i want to extract the text ocr several lines.. not just a word...
Can somone tell me how to use a RE for this?
Thanks!

 
0
 

You should really start a new thread of your own!

The string function find() can find a subtext within a larger text, as will re.findall(). The advantage of find() is that it will give you the location in the form of an index.

Question Answered as of 4 Years Ago by vegaseat, woooee, ZZucker and 1 other
 
0
 

You should really start a new thread of your own!

The string function find() can find a subtext within a larger text, as will re.findall(). The advantage of find() is that it will give you the location in the form of an index.

Thanks, but i'm a bit unsure on using the index since the length of data tends to change within the search area...

And sorry about not starting a new thread... cos in another hobby forum that i'm part of we try to post questions in a thread thats already started with a similar question so that other readers can also look back on the old answer.. i guess it depends on the forum :)

Thanks again guys. i'm new to DaniWeb and am loving it here! you guys are amazingly helpful!!!

 
0
 

Ah, the pros and cons on posting on an old thread.
If you are interested in a regex solution, I would start a new thread and put regex in the title.

 
0
 

A friend just gave me a basic (not very professinal, but easy to move around) solution... trying that out... if it doesnt work, i sure will throw the problem at you guys again :)

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article