2013-07-02 6 views
-3

정규식을 사용하여 텍스트 문서 안의 한 줄에 특정 단어를 찾으려고합니다. 나는 아래 코드를 사용해 보았지만 제대로 작동하지 않는다.Python RE 텍스트 문서에서 특정 단어 찾기

import re 
f1 = open('text.txt', 'r') 
for line in f1: 
    m = re.search('(.*)(?<=Dog)Food(.*)', line) 
    m.group(0) 
    print "Found it." 
f1.close() 

오류 :

Traceback (most recent call last): 
    File "C:\Program Files (x86)\Microsoft Visual Studio 11.0 
ns\Microsoft\Python Tools for Visual Studio\2.0\visualstudi 
0, in exec_file 
    exec(code_obj, global_variables) 
    File "C:\Users\wsdev2\Documents\Visual Studio 2012\Projec 
TML Head Script\HTML_Head_Script.py", line 6, in <module> 
    m.group(0) 
AttributeError: 'NoneType' object has no attribute 'group' 
+1

'아무튼 무엇 제대로 작동합니까? 설명해주십시오. – TerryA

+0

내가 오류를 추가했습니다. –

+0

답변 추가 : – TerryA

답변

3

경기가 발견되지 않았기 때문에 당신이 AttributeError: 'NoneType' object has no attribute 'group'을 받고 있습니다. 일치가없는 경우

re.search()

None를 반환합니다, 그래서 당신은이 작업을 수행 할 수 있습니다

import re 
with open('text.txt', 'r') as myfile: 
    for line in myfile: 
     m = re.search('(.*)(?<=Dog)Food(.*)', line) 
     if m is not None: 
      m.group(0) 
      print "Found it." 
      break # Break out of the loop 

편집 : 나는 당신의 코드 내 대답을 편집했습니다. 자동으로 나중에 파일을 닫습니다 (그리고 정말 멋진 외모 : P)로서 또한, 나는 여기 with/as을 사용했습니다

+0

if 문을 for 루프 끝에 추가하려고 시도했지만 작동하지 않았습니다. 위의 코드에이 코드를 올바르게 구현하는 방법을 보여 주시겠습니까?약간의 혼란이있는 것 같습니다. –

+0

@ NoahR 내 대답을 편집했습니다. – TerryA

+0

그것은 나에게 오류를주지 않았지만 아무런 결과도 반환하지 않습니다. 파이썬에서 정규 표현식을 처음 사용했는데, 내가 사용한 표현이 맞습니까? –

0

프로그램에 몇 가지 문제가 있습니다

  • m은 아무도 없을 것이다는 경우가 이 줄에서 일치하지 않으므로 프로그램이 충돌합니다.

  • 코드가있는 경우 해당 줄에서 첫 번째 일치 항목 만 찾습니다. 모든 일치 항목을 반복하는 대신 re.finditer() method을 사용할 수 있습니다.

  • 단어 전후에 .*을 사용하면 DogFooding과 같이 다른 단어의 중간에 단어가 나타나는 경우 해당 단어와 일치합니다. 이것은 아마도 당신이 원하는 것이 아닙니다. 당신은 아마 수동으로 탈출 백 슬래시를 두 배로 대신 특별한 r'' raw string syntax를 사용하는 것이 좋습니다

    \b Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character…

    로 대신 re documentation 설명 당신의 경기에서 마법 \b 원자를 사용할 수 있습니다.

  • (.*)을 사용하면 일치하는 단어 전후에 어떤 일이 발생하는지 찾기 위해 정규 표현식을 사용하기가 어려워집니다. 단어가 여러 번 나타난다하더라도 중첩되지 않는 일치가 없기 때문입니다. 대신 match.start()match.end() 메서드를 사용하여 일치하는 문자 위치를 가져옵니다. Python의 match objects are documented online.

이를 고려하여, 코드가된다 :

#!/usr/bin/env python2.7 

import re 
f1 = open('text.txt', 'r') 
line_number = 1 
for line in f1: 
    for m in re.finditer(r'\bDogFood\b', line): 
     print "Found", m.group(0), "line", line_number, "at", m.start(), "-", m.end() 
    line_number += 1 
f1.close() 

실행이를 사용하여 text.txt입니다 :

This Food is good. 
This DogFood is good. 
DogFooding is great. 
DogFood DogFood DogFood. 

프로그램 인쇄 :

Found DogFood line 2 at 5 - 12 
Found DogFood line 4 at 0 - 7 
Found DogFood line 4 at 8 - 15 
Found DogFood line 4 at 16 - 23