搜索()再次调用时返回None

2024-10-03 09:16:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次在python中使用re-package。在

为了更好地理解这首诗,我决定把一首诗复制到我的档案里,然后玩玩搜索()使用不同的正则表达式。在

我从下面的网站上找到了这首诗,并把它复制到我的文本文件中: http://www.poets.org/poetsorg/poem-day

为了帮助解决我的问题,我还提到了thisthisthis和{a5}。在

以下是我的代码:

searchFile = open ('/Users/admin/Documents/Python/NLP/Chapter1-TextSample.txt', 'r')

for line in searchFile:
    if re.search('[pP]igeons', line):
        print line

The pigeons ignore us gently as we
scream at one another in the parking
lot of an upscale grocer. 

Pigeons scoot,and finches hop, and cicadas shout and shed
themselves into loose approximations of what
we might have in a different time called heaven.


for line in searchFile:
    if re.search('[pP]igeons', line):
        print line


for line in searchFile:
    print line

如你所见,当我第一次搜索时,我得到了正确的结果。没有问题。但是,一旦我再次执行相同的搜索,或者即使我只是尝试打印文件的行,也不会显示任何内容。但是,当我检查“searchFile”对象时,它仍然存在,如下所示:

^{pr2}$

有人能告诉我为什么会这样吗?我错过什么了吗?在


Tags: andofinrepackageforsearchif
3条回答

因为在第一个循环之后,你已经到达了文件的结尾。另外,您应该使用with()语句打开并自动关闭文件。在

with open('.../Chapter1-TextSample.txt', 'r') as searchFile:
    for line in searchFile:
        if re.search('[pP]igeons', line):
            print line
    searchFile.seek(0)
    # loop again

实际上,这个问题不是关于re,而是关于searchFile。在

当您从文件中读取或迭代时,实际上是在使用该文件。参见:

>>> f = open("test")
>>> f.read()
'qwe\n'
>>> f.read()
''

您可以将文件读取一次到变量,然后从中使用它,例如:

^{pr2}$

您已到达文件的结尾。您应该能够这样做以回到开头:

searchFile.seek(0)

相关问题 更多 >