Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 再次调用时,re.search()返回None_Python_Regex - Fatal编程技术网

Python 再次调用时,re.search()返回None

Python 再次调用时,re.search()返回None,python,regex,Python,Regex,这是我第一次在python中使用re包 为了更好地理解它,我决定将一首诗复制到我的文件中,并使用不同的正则表达式处理re.search() 我从以下网站获得了这首诗,并将其复制到我的文本文件中: 我也提到了,为了帮助解决我的问题 以下是我的代码: searchFile = open ('/Users/admin/Documents/Python/NLP/Chapter1-TextSample.txt', 'r') for line in searchFile: if re.searc

这是我第一次在python中使用re包

为了更好地理解它,我决定将一首诗复制到我的文件中,并使用不同的正则表达式处理re.search()

我从以下网站获得了这首诗,并将其复制到我的文本文件中:

我也提到了,为了帮助解决我的问题

以下是我的代码:

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”对象时,它仍然存在,如下所示:

In[23]:  searchFile
Out[23]: <open file '/Users/admin/Documents/Python/NLP/Chapter1-TextSample.txt', mode 'r' at 0x103a85d20>
[23]中的
:搜索文件
出[23]:

有人能强调一下为什么会发生这种情况吗?我遗漏了什么吗?

您已到达文件末尾。您应该能够这样做,回到开头:

searchFile.seek(0)

因为在第一次循环之后,您已经到达了文件的末尾。此外,您应该使用
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()
''
您可以将文件读取一次到一个变量,然后从那里使用它,如:

l = searchFile.readlines()

for i in l:
   ...

for i in l:
   ...

真的应该有一个傻瓜来结束这对。。。但是我找不到它!好。。。除非你这么做,否则我将投票表决这个问题。@matsjoyce也许就是我报道的那个人?啊,一定是用错了搜索词。问题当心。好的。我不认为这是一个文件结束的问题,因此,这个问题…现在这是有意义的。谢谢根据评论,我对代码进行了如下编辑:
搜索文件中的行:如果重新搜索('[pP]igeon',line):打印行搜索文件.seek(0)
我现在可以多次运行此操作,它将复制结果。