python - 특정 문자열 제거

0

python 기초

목록 보기
3/3
post-thumbnail
  • 말뭉치를 전처리하다보면 불필요한 문자열을 제거해야 할 때가 있다.
  • 정규식(re)을 사용하고 sub 함수를 통해서 제거
  • '\'는 정규식 메타 문자가 아닌 기호로 사용되는 문자를 표시, '|'는 or 조건을 가리킨다.
import re

for idx, file in enumerate(sorted(f_list)):
    new_lines =[]
    with open(file, 'r') as read_file:
        lines = read_file.readlines()
        for line in lines:
            txt = re.sub("\(SP:\)|\(NO:\)|\(FP:\)|\(SN:\)|\(SP:|\(NO:|\(FP:|\(SN:|\(|SP|NO|FP|SN|sp|no|fp|sn|:|\*|\)", "", line)
            new_lines.append(txt)

    with open(f'file_name_{idx+1}.txt', 'w', encoding='utf-8') as outfile:
        outfile.writelines(new_lines)
profile
나 응애👶 개발자, 딥린이👨‍💻, 언어 연구자 👨‍🎓

0개의 댓글