逐行读取文件并传递给方法

时间:2013-08-11 14:45:53

标签: python

我有一个大约10个句子的文本文件。

My Name is Kerry.
I am a female.
My pet is a cat.
It's name is Ronald.
I hate rats.

我想要做的是从这个文本文件中读取一个句子并将其传递给我所写的fineSearch方法。

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.

当我通过fineSearch(ws)时,它可以工作,但是当我打印显示的文本时,它会读取整个文件; My Name is Kerry.\n I am a female.\n My pet is a cat\n等等。我只想在我写的方法中发送一行。

1 个答案:

答案 0 :(得分:2)

如果您需要代码在一行上工作,则需要更改fineSearch(...)函数,如下所示:

def fineSearch(wd):
    for word in wd.strip().split():
            if word.endswith(('ts.','ld.')): # test for ld. at end
                print word

然后,您可以使用以下代码逐行遍历文件。

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

您的初始代码似乎在行列表上工作,类似readlines(...)会提供,但readlines(...)将整个文件读入内存,而您似乎想逐行遍历文件