1. 텔레그램 채팅방으로부터 말뭉치 데이터 얻기

2023. 9. 16. 14:59개인 프로젝트/📚 자연어 처리

# JSON 파일을 읽어오는 함수
# 텔레그램에서 추출한 대화 데이터 파일을 user, text 형태의 csv파일로 추출
import json
import csv


def read_json_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as json_file:
        data = json.load(json_file)
    return data


def extract_actor_text_to_csv(json_data, output_csv_file):
    with open(output_csv_file, 'w', newline='', encoding='utf-8') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(["Actor", "Text"])
        prev_actor = None
        prev_text = []

        for message in json_data.get("messages", []):
            actor = message.get("from", "") if message.get(
                "from") else message.get("actor", "")
            text = message.get("text", "")

            try:
                # 'text' 필드가 문자열이 아닌 경우 처리
                if not isinstance(text, str):
                    text = str(text)  # 문자열로 변환

                # 텍스트가 없거나 'link'를 포함하면 무시
                if not text or any('link' in item.get('type', '') for item in message.get("text_entities", [])):
                    continue

                # 줄 바꿈 문자를 공백으로 대체
                text = text.replace("\n", " ")

                if actor == prev_actor:
                    prev_text.append(text)  # 리스트에 텍스트 추가
                else:
                    if prev_actor is not None:
                        # 리스트를 문자열로 합쳐서 쓰기
                        writer.writerow([prev_actor, ' '.join(prev_text)])
                    prev_actor = actor
                    prev_text = [text]  # 리스트로 초기화

            except Exception as e:
                print(f"오류 발생! 메시지: {message}")
                print(f"에러 메시지: {str(e)}")
                # break # 오류가 많이 나면 주석을 푸세요
        # 마지막 줄을 쓰기
        if prev_actor is not None:
            # 리스트를 문자열로 합쳐서 쓰기
            writer.writerow([prev_actor, ' '.join(prev_text)])


# Input: JSON 파일 경로
json_file_path = 'result_test.json'

# Output: CSV 파일 경로
output_csv_file_path = 'output.csv'

json_data = read_json_file(json_file_path)
extract_actor_text_to_csv(json_data, output_csv_file_path)
print(f"데이터 추출 및 저장이 완료되었습니다. {output_csv_file_path} 파일을 확인하세요.")

  위는 소스코드 전문입니다. 이와 같이 처리를 할 경우 채팅방 기록에 있는 모든 사람의 대화 기록이 Actor, Text 형식으로 추출됩니다.

  • 한 문장을 여러 번의 줄바꿈을 사용하여 메세지를 보낸 경우 한 문장으로 합쳐서 csv파일로 기록합니다.
  • 빈 메세지이거나 하이퍼링크를 공유한 경우는 추출이 되지 않도록 필터를 걸었습니다.

 


  그러나 위와 같은 경우 자연어 처리를 할 때 특정인의 말투를 따라하고 싶은 경우에는 불필요한 많은 데이터가 있습니다. 그래서 원하는 타겟만 걸러주는 코드를 새로 작성했습니다.

# JSON 파일을 읽어오는 함수
# 텔레그램에서 추출한 대화 데이터 파일을 user, text 형태의 csv파일로 추출
# 특정인의 발언만 기록하는 기능 개선
import json
import csv


def read_json_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as json_file:
        data = json.load(json_file)
    return data


def extract_actor_text_to_csv(json_data, output_csv_file, target_name):
    with open(output_csv_file, 'w', newline='', encoding='utf-8') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(["Actor", "Text"])
        for message in json_data.get("messages", []):
            actor = message.get("from", "") if message.get(
                "from") else message.get("actor", "")
            text = message.get("text", "")

            try:
                # 'text' 필드가 문자열이 아닌 경우 처리
                if not isinstance(text, str):
                    text = str(text)  # 문자열로 변환

                # 텍스트가 없거나 'link'를 포함하면 무시
                if not text or any('link' in item.get('type', '') for item in message.get("text_entities", [])):
                    continue

                # 줄 바꿈 문자를 공백으로 대체
                text = text.replace("\n", " ")

                if actor == target_name:
                    # 추출 대상 사용자와 일치하면 CSV 파일에 쓰기
                    writer.writerow([actor, text])

            except Exception as e:
                print(f"오류 발생! 메시지: {message}")
                print(f"에러 메시지: {str(e)}")
                # break # 오류가 많이 나면 주석을 푸세요


# JSON 파일 경로
json_file_path = 'result_test.json'  # 실제 JSON 파일 경로로 변경하세요.

# 추출하고자 하는 특정 대상
target_name = '홍길동'  # 실제 대상 이름으로 변경하세요.

# CSV 파일 경로
output_csv_file_path = f'output_{target_name}.csv'

json_data = read_json_file(json_file_path)
extract_actor_text_to_csv(json_data, output_csv_file_path, target_name)
print(f"데이터 추출 및 저장이 완료되었습니다. {output_csv_file_path} 파일을 확인하세요.")
  • 원하는 사람만의 대화 기록을 저장합니다.
  • 원문을 가공하지 않고 그대로 저장하되, 텍스트가 없는 내용이거나 하이퍼링크 공유인 경우는 저장하지 않도록 설정하였습니다.

  맨 처음 코드와 다른 점은 위에 상술한 두 가지입니다.