2013-08-20 1 views
2

많은 텍스트 줄이 포함 된 txt 파일 (myText.txt)이 있습니다.일부 단어를 제거하면 txt 파일의 다른 단어가 대체됩니다.

내가 알고 싶습니다 :

  • 방법 (I 단어 나 자신을 설정할)
  • 어떻게 단어의 목록을 작성하는 을 삭제해야 할 단어의 목록을 작성

    The ancient Romans influenced countries and civilizations in the following centuries. 
    Their language, Latin, became the basis for many other European languages. They stayed in Roma for 3 month. 
    
    : 그 myText.txt 인 경우 예를 들어

을 교체해야합니다

  • 내가 제거 할 것이다 "는" "와"나는 대체 싶습니다 "의" "고대" "이전"에 의해
  • 내가 년 "에 의해"달 "과"세기 " 대체하려는
  • "

답변

3

당신은 항상 정규식을 사용할 수 있습니다. 다음과 같이 보일 것입니다 :

def processTextFile(filename_in, filename_out, delWords, repWords): 


    with open(filename_in, "r") as sourcefile: 
     for line in sourcefile: 
      for item in delWords: 
       line = line.replace(item, "") 
      for key,value in repWords.items(): 
       line = line.replace(key,value) 

      with open(filename_out, "a") as outfile: 
       outfile.write(line) 



if __name__ == "__main__": 
    delWords = [] 
    repWords = {} 

    delWords.extend(["the ", "and ", "in "]) 
    repWords["ancient"] = "old" 
    repWords["month"] = "years" 
    repWords["centuries"] = "years" 

    processTextFile("myText.txt", "myOutText.txt", delWords, repWords) 

참고로, 이것은 item()을 사용하는 이유입니다. 파이썬 2.x를 사용하는 경우 iteritems()를 사용하십시오. 특히 큰 텍스트 파일의 경우 더 효율적이라고 생각합니다.

+0

안녕하세요. 매우 잘 작동합니다. 가끔은 내 텍스트에 "+"와 "-"기호가 있습니다. 그러나 파이썬은 삭제를 허용하지 않는 것처럼 보입니다. ('and', 'in', 'the', '+', '-') 특수 문자를 입력하는 특별한 방법이 있습니까? 고마워. – S12000

+0

'+'와'-'와 같은 정규 표현식에 의미가있는 특정 문자가 있습니다. 제 제안은 정규 표현식 튜토리얼 사이트에서 시간을 보내고 그 문자를 배우는 것입니다. [Regex101] (http://www.regex101.com)은 좋은 것입니다. – dawg

2

트릭을 수행해야합니다. 목록을 사용하여 삭제할 개체를 저장 한 다음 목록을 반복하고 목록의 모든 요소를 ​​내용 문자열에서 제거합니다. 그런 다음 사전을 사용하여 현재 가지고있는 단어와 바꾸려는 단어를 저장합니다. 또한 이들을 반복하고 현재 단어를 바꾸는 단어로 바꿉니다.

import re 

st='''\ 
The ancient Romans influenced countries and civilizations in the following centuries. 
Their language, Latin, became the basis for many other European languages. They stayed in Roma for 3 month.''' 

deletions=('and','in','the') 
repl={"ancient": "old", "month":"years", "centuries":"years"} 

tgt='|'.join(r'\b{}\b'.format(e) for e in deletions) 
st=re.sub(tgt,'',st) 
for word in repl: 
    tgt=r'\b{}\b'.format(word) 
    st=re.sub(tgt,repl[word],st) 


print st 
+0

도움 주셔서 감사합니다. 오류 메시지가 나타납니다. "AttributeError : 'dict'객체에 'iteritems'속성이 없습니다."필자는 Python의 최신 버전입니다. 정상입니까? 고맙습니다. – S12000

+0

파이썬 3을 사용하는 경우 replaceWords.items()라고 말하십시오 –

+0

덕분에 부탁드립니다. – S12000

2

교체에 대한 삭제 및 사전에 대한 목록을 사용하여

def replace(): 
    contents = "" 
    deleteWords = ["the ", "and ", "in "] 
    replaceWords = {"ancient": "old", "month":"years", "centuries":"years"} 

    with open("meText.txt") as f: 
    contents = f.read() 
    for word in deleteWords: 
    contents = contents.replace(word,"") 

    for key, value in replaceWords.iteritems(): 
    contents = contents.replace(key, value) 
    return contents 
+0

이 코드를 이용해 주셔서 감사합니다. 와우 거기에 내 목표를 달성하는 많은 방법이 있습니다 :) – S12000

관련 문제