2015-01-12 6 views
0

저는 텍스트 파일을 편집하는 프로그램을 작성하고 있습니다. 나는 프로그램이 중복 된 문자열을 찾아 n - 1 줄의 비슷한 문자열을 삭제하려고한다.사전에서 키를 사용하여 문자열을 검색하는 방법은 무엇입니까?

import re 

fname = raw_input("File name - ") 
fhand = open(fname, "r+") 
fhand.read() 


counts = {} 
pattern = re.compile(pattern) 

# This searches the file for duplicate strings and inserts them into a dictionary with a counter 
# as the value 

for line in fhand: 
    for match in pattern.findall(line): 
     counts.setdefault(match, 0) 
     counts[match] += 1 

pvar = {} 

#This creates a new dictionary which contains all of the keys in the previous dictionary with 
# count > 1 

for match, count in counts.items(): 
    if count > 1: 
     pvar[match] = count 

fhand.close() 
count = 0 

# Here I am trying to delete n - 1 instances of each string that was a key in the previous 
# dictionary 

with open(fname, 'r+') as fhand:   
    for line in fhand: 
     for match, count in pvar.items(): 
      if re.search(match, line) not in line: 
       continue 
       count += 1 
      else: 
       fhand.write(line) 
print count 
fhand.close() 

가 어떻게 코드 작업의 마지막 비트를 만들 수 있습니다 여기에

내가 지금까지 가지고있는 스크립트입니다? 사전에서 키를 사용하여 관련 줄을 식별하고 n-1 개의 인스턴스를 삭제할 수 있습니까? 아니면 완전히 잘못하고 있습니까?

EDIT : 파일의 샘플로, 각 'XYZ'인스턴스가 두 개의 공백 문자가있는 개행 문자로 된 목록이어야합니다. 서식이 조금 INPUT

-=XYZ[0:2] & 
-=XYZ[0:2] & 
-=XYZ[3:5] & 
=XYZ[6:8] & 
=XYZ[9:11] & 
=XYZ[12:14] & 
-=XYZ[15:17] & 
=XYZ[18:20] & 
=XYZ[21:23] & 

OUTPUT

= XYZ 내 사과, 엉망 [0 : 2]

또한 편집

는 사람이 이유를 설명 할 수 코드의 마지막 부분은 아무 것도 반환하지 않습니까?

+0

XYZ 인스턴스를 어떻게 의미합니까? Sry 나는 정말로 이해하지 못한다. 나는 심지어 입력 파일을 이해하지도 않는다. – ProgrammingIsAwsome

+0

그냥 'XYZ'가있는 줄을 지우고 싶습니다. –

+0

하지만 모두 'XYZ'가 포함되어 있습니다 : – BartoszKP

답변

0

여기 (... 아마 문제가되지 않습니다, 라인이 정렬되지 않은 그래서) 사전을 사용하여 정규 표현식을 사용하지 않고 뭔가 :

#!/usr/bin/env python 

import os 
res = {} 
with open("input.txt") as f: 
    for line in f.readlines(): 
     line = line.strip() 
     key = line.split('[')[0].replace('-','').replace('=', '') 
     if key in res: 
      continue 
     res[key] = line 
     # res[key] = line.replace('&', '').strip() 
print os.linesep.join(res.values()) 

이 후행 앰퍼샌드를 제거하지 않습니다. 주석 처리를 제거하려면 다음을 수행하십시오.

res[key] = line.replace('&', '').strip() 
+0

정규식을 사용하여 이것을 작성할 수 있습니까? 순서대로 작성해야합니다. –

+0

@VladimirEmelianov 'OrderedDict'를 사용할 수 있습니다. 또는'list'와 같은 정렬 된 구조체를 사용하십시오. 조금 더 많은 라인이 될 것입니다. –

+0

고맙습니다! –