2014-11-25 2 views
0

나는 파이썬을 배우고 있으며, 사소한 문제라고 생각합니다. 해당 구분 기호가 해당 줄에 없으면 텍스트 파일의 각 줄 끝에 // 구분 기호를 추가하려고합니다.파이썬 : 누락 된 구분 기호를 찾아 텍스트 파일에 추가하는 방법

예 텍스트 파일 'example.txt':이 예제 텍스트 파일에서

A string of information that does not require the delimiter 
95 full !oe, !oeha // 
96 new kaba 
100 name !uo5 // 

, 나는 그 라인의 위치를 ​​96 내 전략을 시작하는 줄의 끝에 // 추가 소원이 구분 기호 (즉, 숫자로 시작하는 줄)를 필요로하는지, // 존재하는지 테스트하고, // 존재하지 않으면 해당 줄의 끝 부분에 //를 추가하십시오. 다음과 같이 내 코드는 다음과 같습니다

import re 
infile = open("example.txt", 'r+w') 

for line in infile: 
    m = re.match(r'(\d+)\s+\w+\s+([^/]+)', line) 
    if m: 
     test = line.find('//') 
     if test == -1: 
      infile.write(line + ' // \n') 
     continue 

내 example.txt 파일의 출력은 다음과 같습니다 infile.write(line + ' // \n')이 .txt 인 파일에 새 줄을 추가하기보다는 부족한 라인을 교체 이유는 무엇

A string of information that does not require the delimiter 
95 full !oe, !oeha // 
96 new kaba 
100 name !uo5 // 
96 new kaba 
// 

구분 기호? 또한 구분 기호가 같은 줄에 표시되지 않는 이유는 무엇입니까?

infile.write(line + ' // \n') 대신 infile.replace(line, line + ' // \n')을 사용했지만 오류 메시지 AttributeError: 'file' object has no attribute 'replace'이 표시되었습니다.

+0

앞에'\ n' 느릅 나무 루프 – nu11p01n73R

답변

1

re.sub 기능을 사용하면 코드를 단순화 할 수 있습니다.

^(\d+.*)(?<!//)$ 

사용 예 :

>>> file = open('input', 'r') 
>>> for line in file: 
...  print re.sub(r'^(\d+.*)(?<!//)$', r'\1//', line), 

A string of information that does not require the delimiter 
95 full !oe, !oeha // 
96 new kaba// 
100 name !uo5 // 

와 같은 출력을 생성 싶은 정규식

  • ^ ANC 문자열의 처음에 정규 표현식을 붙입니다.

  • \d+ 임의의 수의 문자열과 일치합니다. 앵커 라인이 라인

  • (?<!//) 부정적인 lookbehind의 끝날 때까지 아무것도 일치하는 자리

  • .*로 시작되도록합니다. 문자열의 끝 것을 $\1 // .See 데모에 의해 문자열

+0

의에서'line' 변수에 읽어 주셔서 감사합니다! 're.sub()'함수를 지적 해 주셔서 감사합니다. – acd

+0

@ user3731769 당신은 오신 것을 환영합니다. 다행 이네요. – nu11p01n73R

0
^(?=\d+(?:(?!\/\/).)*$)(.*) 

해보십시오 this.Replace의 끝에 //

  • $ 앵커하여 정규식을 presceded되지 않은 주장한다. file.read 의해

    import re 
    p = re.compile(ur'^(?=\d+(?:(?!\/\/).)*$)(.*)', re.MULTILINE) 
    test_str = u"A string of information that does not require the delimiter\n95 full !oe, !oeha //\n96 new kaba\n100 name !uo5 //\n100 name !uo5 " 
    subst = u"\1 //" 
    
    result = re.sub(p, subst, test_str) 
    

    http://regex101.com/r/rA7aS3/13

    교체 test_str().

  • 0

    라인이 숫자/숫자로 시작하고 바로 줄 바꿈을 제거 "//"로 끝나지 않는 경우는, 정규식이 필요하지 않습니다 덮어 업데이트 된 라인을 작성하는 w 모드에서 다시, 마지막에 "//\n"를 추가합니다.

    0

    필자는 입력 대신 출력용으로 다른 파일을 사용하고 실제로 교체해야하는 경우 수동으로 뒤 씁니다. 나는 파이썬 2.7에서 다음을했다 :

    라인이 이미 분리되어 있기 때문에 그것은에 의해 새로운 라인에서 apears
    import re 
    
    # Open an output file distinct from the input file 
    infile = open("example.txt", 'r') 
    outfile = open("output.txt", 'w') 
    
    for line in infile: 
        # Newline already present in input line - rstrip() to kill it 
        result = line.rstrip() 
        m = re.match(r'(\d+)\s+\w+\s+([^/]+)', result) 
        if m: 
         test = result.find('//') 
         if test == -1: 
    
          # Add the delimiter 
          result += ' //' 
    
        # Just write the original line if no changes were needed 
        outfile.write(result + "\n") 
    
    # Close the streams 
    infile.close() 
    outfile.close() 
    
    +0

    감사합니다. rchang. 실제로 출력을 위해 다른 파일을 사용하고 있지만 설명을 위해 코드를 단순화하려고했습니다. 당신이 만든 몇 가지 포인트를 사용하여 문제를 해결했습니다. 감사합니다! – acd

    관련 문제