2014-12-15 7 views
2

이것은 파이썬에서 re 패키지를 처음 사용하는 것입니다.re.search()는 다시 호출 할 때 None을 반환합니다.

더 잘 이해하기 위해 나는시를 내 파일에 복사하고 다른 정규식을 사용하여 re.search()를 사용하여 놀았습니다.

나는 다음 웹 사이트에서시를 가지고 내 텍스트 파일에 복사 : http://www.poets.org/poetsorg/poem-day

나는 또한 내 문제를 해결하는 데 도움이하기 위해 this, this, thisthis 언급했다. 당신이 볼 수 있듯이 내가 처음 검색 할 때

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> 

누군가가이 문제가 발생하는 이유를 강조 할 수 있습니까? 내가 놓친 게 있니?

답변

3

파일의 끝에 도달했습니다. 처음으로 돌아가려면이 작업을 수행 할 수 있어야합니다.

searchFile.seek(0) 
+1

정말에이를 닫습니다 속는 사람이 있어야한다 ... 그러나 나는 '수 그것을 찾지 마라! – matsjoyce

+0

글쎄 ... 당신이 할 때까지, 나는 질문을 upvoting. – Kevin

+0

@matsjoyce가 내가보고 한 것일 수도 있습니다. –

1

첫 번째 루프가 끝나면 파일의 끝에 도달했기 때문입니다. 또한 파일을 열고 자동 닫으려면 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 
1

사실,이 문제는이 searchFile에 관하여, re로하지 않습니다.

파일을 읽거나 그 파일에서 반복 할 때 실제로 파일 크기는 이 (가)입니다.

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

당신은 변수에 한 번 파일을 읽을 수 있고, 같은, 거기에서 그것을 사용 : 참조

l = searchFile.readlines() 

for i in l: 
    ... 

for i in l: 
    ... 
관련 문제