import pandas as pd
import re
# 문자열의 줄 바꿈과 연속된 공백을 삭제하는 함수
def remove_newlines(text):
text = re.sub(r'\n', ' ', text) # 줄 바꿈을 공백으로 대체
text = re.sub(r' +', ' ', text) # 연속된 공백을 하나의 공백으로 대체
return text
# 텍스트 파일을 읽어서 DataFrame으로 변환하는 함수
def text_to_df(data_file):
texts = [] # 텍스트를 저장할 리스트
with open(data_file, 'r', encoding='utf-8') as file:
text = file.read() # 파일 내용을 문자열로 불러오기
sections = text.split('\n\n') # 줄 바꿈으로 문자열을 두 줄로 나누기
for section in sections:
lines = section.split('\n') # 섹션을 줄 바꿈으로 나누기
fname = lines[0] # "lines" 목록의 첫 번째 요소를 얻기
content = ' '.join(lines[1:]) # 'lines' 목록의 두 번째 이후 요소를 얻기
texts.append([fname, content]) # 타이틀과 내용을 리스트에 추가
df = pd.DataFrame(texts, columns=['fname', 'text']) # 리스트를 DataFrame으로 변환
df['text'] = df['text'].apply(remove_newlines) # 'text' 열에 있는 텍스트에 remove_newlines 함수 적용
return df # DataFrame 반환
df = text_to_df('./02_hotel_chatbot/data.txt') # 'data.txt' 파일을 읽어서 DataFrame으로 변환
df.to_csv('./02_hotel_chatbot/data.csv', index=False, encoding='utf-8') # DataFrame을 CSV 파일로 저장