2016-06-21 1 views
0

기본적으로 텍스트 파일이 있고 문장의 중간 단어를 검색하려고합니다. 내 .py 스크립트를 실행할 때 found_state not defined이라고 말하는 오류가 발생합니다. 텍스트 파일의 중간에 특정 단어를 찾는 Python 정규식

이 파일을 고려하십시오 : 당신의 상태 if re.search('(?<=#)\w+',data): 다음 found_state이 선언되지 않은, 실패하면

import re;  
import time; 

with open('file.conf') as f: 
    content = f.readlines() 
name='' 

for data in content: 
    if re.search('(?<=#)\w+',data): 
     found_state=1 
     name=data 
     break 
if found_state==1: 
    print name + "is Found" 
else: 
    print "NF" 
+0

그래서 'found_state'를 미리 선언하십시오. 스크립트는 어디서 사용합니까? 변수를 먼저 선언하는 것 외에도'if' 블록 안에'global found_state'를 지정하고'1'에 할당해야 할 수도 있습니다. –

+0

자, 아마도'r '# (\ w +)''와'.group (1)'만 있으면 될까요? https://ideone.com/HdPCEt를 참조하십시오 –

+0

약간의 서식을 개선했습니다 – AlBlue

답변

0

당신은 "중간 단어"를 얻을 필요가 있다고 말하면서 나는 이라는 단어가이라는 단어가 필요하다는 것을 알았습니다. 일치하는 것이 있으면 지금 전체 라인을 얻습니다.

import re; 
content = ["hostname(config)#aaa new-model", "fdfsfd b", "kthik", "pooooo", "shh"] # <= TEST DATA 
name='' 
found_state = 0      # Declare found_state 
for data in content: 
    m = re.search(r'#(\w+)',data)  # Use a raw string literal and a capturing group 
    if m:        # Check if there was a match and if yes 
     found_state=1     # - increment found_state 
     name=m.group(1)    # - get the word after # 
     break 
if found_state==1: 
    print name + " is Found" 
else: 
    print "NF" 

하지만, 아마도 당신이 this demo를 참조

res = [] 
for data in content: 
    res.extend(re.findall(r'#(\w+)', data)) 
print(res) 

에 코드를 줄이고 싶어 : 여기

은 (는 aaa is Found을 인쇄) 당신을 위해 일해야한다는 a piece of code입니다. #(\w+) 패턴은 # 뒤에 단어 문자 (1 이상)를 캡처하고 캡처 된 부분 문자열 만 반환하고 extend은 모든 문자를 목록에 추가합니다.

+1

고맙습니다. – GoluBoss

0

:

file.conf 
hostname(config)#aaa new-model 
fdfsfd b 
kthik 
pooooo 
shh 

내 파이썬 스크립트는 것 같습니다. for 루프 전에 수행하십시오.

+0

텍스트 파일에서 #aaa를 찾으려면 정규식이되어야합니다. – GoluBoss

+0

당신은 여기에 당신의 정규식을 시도 할 수 있습니다 : https://regex101.com/ –

+0

누군가가 파이어 스크립트 스크립트를 실행하는 데 아무런 결과를 얻지 못하여 특정 정규 표현식으로 나를 안내 할 수 있습니까? – GoluBoss

관련 문제