저는 텍스트 파일을 편집하는 프로그램을 작성하고 있습니다. 나는 프로그램이 중복 된 문자열을 찾아 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]
또한 편집
는 사람이 이유를 설명 할 수 코드의 마지막 부분은 아무 것도 반환하지 않습니까?
XYZ 인스턴스를 어떻게 의미합니까? Sry 나는 정말로 이해하지 못한다. 나는 심지어 입력 파일을 이해하지도 않는다. – ProgrammingIsAwsome
그냥 'XYZ'가있는 줄을 지우고 싶습니다. –
하지만 모두 'XYZ'가 포함되어 있습니다 : – BartoszKP