2017-03-08 1 views
0

내가 각 행은 단어의 목록/문자열 인 경우이파이썬에서는 사전을보고 모든 행의 텍스트를 바꾸는 방법은 무엇입니까?

id details 
    1 I have an account 
    2 acnt is now closed 
    3 he knws my acc no 

와 같은 데이터 세트 사전

d ={'acc' : 'account', 'acnt' : 'account', 'knws':'knows'} 

방법을 대체 할 수있는 모든 단어가있는 경우? 또한 데이터 세트에는 50 만 개의 행이 있습니다.

출력은이 무차별 일이다이

id details 
    1 I have an account 
    2 account is now closed 
    3 he knows my account no 

답변

0

싶습니다, 나는 생각한다. 우선, 파일의 줄을 읽고 변경된 텍스트를 새 파일에 써야합니다.

텍스트의 각 행에 대해 사전의 모든 키를 찾아 필요한 대체 단어를 만듭니다. 그 부분은 다음과 같이 보일 것입니다 :

for line in input_file: 
    for word in abbrev_dict: 
     if word in line: 
      line = line.replace(word, abbrev_dict[word]) 
    # write the altered line to the output file 

솔루션으로 나아갈 수 있습니까?

0

신속하고 더러운 방법

with open('bigfile') as f: 
     for line in f: # iterate over each line and replace words with alias 
       print " ".join([d.get(w,w) for w in line.split(" ")] # your desired output 
관련 문제