0

我有一个包含大约 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

主要的

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等等。我只想能够向我编写的方法发送一行。

4

1 回答 1

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(...)将整个文件读入内存,而您似乎想逐行迭代文件。

于 2013-08-11T14:51:34.643 回答