한글패치 관련 짧은 글들

텍스트 파일 내용 교체 (csv이용)

Snowyegret 2021. 8. 9. 09:58

출처: https://devpouch.tistory.com/55

출처: https://www.studytonight.com/python-howtos/search-and-replace-a-text-in-a-file-in-python

 

 

https://pastebin.com/ChyPpD1E

# importing the regex module
import re
import csv


# defining the replace method
def replace(file_path, text, subs, flags=0):
    with open(file_path, "r+", encoding='utf-8') as file:
        # read the file contents
        file_contents = file.read()
        text_pattern = re.compile(re.escape(text), flags)
        file_contents = text_pattern.sub(subs, file_contents)
        file.seek(0)
        file.truncate()
        file.write(file_contents)


def reformatt_string(input_text):
    return '\"val\": \"'+input_text+'\",'


file_path = "dialogues-jp.txt"
csv_path = "test.csv"

f = open(csv_path,'r', encoding='utf-8')
rdr = csv.reader(f)

for findincsv in rdr:
    string_replaced = reformatt_string(findincsv[0])
    new_string = reformatt_string(findincsv[1])
    replace(file_path, string_replaced, new_string)

 

def reformatt_string(input_text):

    return '\"val\": \"'+input_text+'\",'

검색/대체할 텍스트의 앞/뒷부분을 input_text의 앞/뒤에 넣는다.

 

file_path = "dialogues-jp.txt"

csv_path = "test.csv"

수정할 원본 txt파일과, 수정할 단어가 담겨있는 csv파일의 경로 (첫번째 라인이 원어, 두번째 라인이 번역본)

 

for findincsv in rdr:
    string_replaced = reformatt_string(findincsv[0])
    new_string = reformatt_string(findincsv[1])
    replace(file_path, string_replaced, new_string)

 

findincsv[0]

findincsv[1] ->  첫 번째 라인을 두번째 라인으로 대체한다는 것이므로, 상황에 맞게 수정 가능

 

 

 

사용예시) \n 개행문자가 들어있는 텍스트 파일의 경우

아래 텍스트 파일을 csv로 만들 것인데, \n 개행문자가 있을 시 파이썬에서 줄바꿈이 되므로 미리 변환시켜놓자.

 

1. "바꾸기" 기능을 통해 \n을 다른 문자로 대체

  - 찾기 모드를 일반으로 해야 함.

 

 

 

2. 엑셀-열기-csv 파일로 만들 텍스트 파일을 불러온 후, 알맞게 설정

 

 

 

 

3. 3번째 라인에 뭐 들어있나 검사 후, 이상 없으면 csv 파일로 저장.

  -> 비영어권 문자가 들어있을 시 꼭 "UTF-8"로 저장하기.

  -> 이후 열어서 제대로 되어있나 확인

 

 

 

4. 바꿀 텍스트 파일의 원본 형식 찾기. 위 같은 경우 stringJP 부분을 바꿀 것이므로 앞 뒤를 저렇게 설정하였다.

이후 바꿀 텍스트 파일에서도 \n을 1번에서 한 것과 동일한 문자로 대체

 

 

 

5. 이러면 csv파일의 1번 열에 있는

"見事に実った麦畑で風が吹くと、{S}風の形がはっきり見えることがある。"가,

파이썬의 reformatt_string 함수에 의해

"     1 string stringJP = "見事に実った麦畑で風が吹くと、{S}風の形がはっきり見えることがある。""로 바뀌게 되고,

이후 아래 텍스트 파일에서 검색하여 바꿔지게 된다.

이 방식의 장점은 사람이 개노가다 하는것과 근본적으로 동일하다는 것이 있으며,

이에 프로그래밍을 몰라도 텍스트 수정이 가능하다.

또한, 앞 뒤로 알맞은 형식을 붙이기 때문에 텍스트가 부분적으로 바뀔 일이 없다는 것이다.

 

 

6. 파이썬을 돌린 후 완성된 결과물에서 {S}를 \n으로 바꿔주면 끝.