Reputation: 3494
I have a text file that has around 10 sentences.
My Name is Kerry.
I am a female.
My pet is a cat.
It's name is Ronald.
I hate rats.
What i want to do is to read a sentence from this text file and pass it on to the fineSearch
method that i have written.
def fineSearch(wd):
for line in wd:
for word in line.strip().split():
if word.endswith(('ts.','ld')):
print word
MAIN
ws = linebylineread('tx.txt')
fineSearch("It's name is Ronald.") # THIS IS FOR DEMO PURPOSE ONLY.
NOTE: I WANT TO READ JUST ONE LINE AT A TIME FROM THE TX.TXT FILE AND PASS IT TO THE METHOD THAT I HAVE WRITTEN.
NOTE: I HAVE NOTICED THAT THE CODE WORKS WHEN I PASS THE WHOLE CHUNK OF TEXT AND NOT A LINE.
When i pass fineSearch(ws)
it works but it reads the entire file, when i print the text it shows as; My Name is Kerry.\n I am a female.\n My pet is a cat\n
etc. I just want to be able to send ONE line to the method i have written.
Upvotes: 0
Views: 84
Reputation: 34493
If you need the code to work on a line, you need to change the fineSearch(...)
function as follows:
def fineSearch(wd):
for word in wd.strip().split():
if word.endswith(('ts.','ld.')): # test for ld. at end
print word
And then, you can iterate over the file line by line using the following code.
>>> with open('testFile.txt', 'r') as f:
for line in f:
fineSearch(line)
rats. # Output. If you wanted Ronald. too, you need to change `ld` in the code to `ld.`
Your initial code seems to work on a list of lines, something like readlines(...)
would provide, but readlines(...)
reads the whole file into memory whereas you seem to want to iterate over the file line by line.
Upvotes: 2