# -*- coding: utf-8 -*-
# Your Python code starts here
import re
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from konlpy.tag import Okt
from translate import Translator
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
# NLTK 데이터 다운로드 (처음 실행 시 한 번 필요)
nltk.download('punkt')
nltk.download('stopwords')
output_file_path = r"C:\Users\찜\Documents\result_output.txt"
# 파일 경로
# file_path = r"C:\Users\찜\최종15.txt"
file_path = r"C:\Users\찜\Documents\rawData.txt"
# 파일에서 텍스트 읽기
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
# 사용자 정의 불용어 리스트, 특허분야 키워드 분석시 일반적으로 제거할 단어 + 특정 주제 분석시 custom
stop_words2 = """상기,수요,통합,제,형성,형태,헬멧,하는,포함,통해,추가로,청구,착용,조건으로서,제,정성분석,있는,이어주는,이루,의해,의한,으로,연결되고,에,안전모,시에,수,서로,상기,사용자,본체,보호구,및,미리,머리,부터,따라,두부,우위,잠재력,우수,가능,기어,로부터,로,으로,제공,방법,기존,데이터,편리,통합.추정,대한,구성,것을,각,helmet,),(.제목,이하,프제,중심,제목,요약,제품,산업 요약:,기술,우수성:,상업,잠재력:,경쟁,우위:,위험,관리:,지속,혁신,개선,향상,장치,보호,안전,성과,통한,시스템,관리,필요,구성,사용자,예상,기능,차별 ,하는,형성,있어,구성,두부,포함,통해,추가로,청구,착용,중,조건,제,정성분석,있는,이어주는,이루어,이루는,이,의해,의한,으로,연결,안전모,시에,수,서로,상기,사용자의,본체의,본체,보호구,및,미리,머리,로,따라,두부가,특징,the,of,to,and,said,있게,대한,는,구성되는,것을,helmet,),하부,위치,기능,기구,제어,구비,설치,연결,구성,외부,내부,사용,방향,동작,수단,모듈,시스템,복수,어셈블리,나타낸,개재,하여""".replace('\n', '').replace(' ', '').split(',')
# 정규표현식을 사용하여 불용어 제거
def remove_custom_stopwords(text, stop_words):
for stop_word in stop_words:
text = re.sub(r'\b' + re.escape(stop_word) + r'\b\s*', '', text)
return text
# '청구항1'을 기준으로 텍스트 분리
patent_claims = text.split('청구항1')
# 중복 제거
unique_claims = list(set(patent_claims))
# 각 청구항에서 불용어 제거
filtered_claims = [remove_custom_stopwords(claim, stop_words2) for claim in unique_claims]
# 개별 데이터 내에서 중복된 단어 제거
def remove_duplicate_words(claim):
words = claim.split()
unique_words = list(set(words))
return ' '.join(unique_words)
unique_filtered_claims = [remove_duplicate_words(claim) for claim in filtered_claims]
# 모든 텍스트를 하나로 합침
filtered_text = ' '.join(unique_filtered_claims)
# 디버깅: 중간 결과 출력
print("Filtered Text:\n", filtered_text[:1000]) # 첫 1000자 출력
# 한국어와 영어를 분리하여 처리
okt = Okt()
korean_tokens = okt.morphs(filtered_text)
# 영어 토큰화 및 불용어 제거
english_stop_words = set(stopwords.words('english'))
english_tokens = [word for word in word_tokenize(filtered_text) if word.isalpha() and word.lower() not in english_stop_words]
# 디버깅: 중간 결과 출력
print("English Tokens:\n", english_tokens[:100]) # 첫 100개 토큰 출력
# 영어 텍스트를 한국어로 번역
translator = Translator(to_lang="ko")
translated_text = translator.translate(' '.join(english_tokens))
# 디버깅: 번역된 텍스트 출력
print("Translated Text:\n", translated_text[:1000]) # 첫 1000자 출력
# 번역된 한국어 텍스트를 토큰화
translated_korean_tokens = okt.morphs(translated_text)
# 한국어 명사만 추출
korean_nouns = [word for word in korean_tokens if word not in stop_words2 and okt.pos(word)[0][1] == 'Noun' and len(word) > 1]
# 번역된 한국어 명사만 추출
translated_korean_nouns = [word for word in translated_korean_tokens if word not in stop_words2 and okt.pos(word)[0][1] == 'Noun' and len(word) > 1]
# 디버깅: 명사 리스트 출력
print("Korean Nouns:\n", korean_nouns[:100]) # 첫 100개 명사 출력
print("Translated Korean Nouns:\n", translated_korean_nouns[:100]) # 첫 100개 명사 출력
# 모든 명사를 결합
all_nouns = korean_nouns + translated_korean_nouns
# 단어 빈도 계산
word_counts = Counter(all_nouns)
# 디버깅: 단어 빈도 출력
print("Word Counts:\n", word_counts.most_common(100)) # 상위 100개 단어 출력
# 한글 폰트 경로 설정
font_path = r'C:\Users\찜\Downloads\malgun-gothic.ttf' # 폰트 파일의 경로를 지정하세요
# 워드 클라우드 생성 (배경색 검정)
if word_counts:
wordcloud = WordCloud(width=800, height=400, background_color='white', font_path=font_path, colormap='inferno').generate_from_frequencies(word_counts)
# 워드 클라우드 시각화
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
else:
print("No words to display in the word cloud.")
# 결과를 텍스트 파일로 저장
def save_to_file(file_path, data):
with open(file_path, 'w', encoding='utf-8') as file:
file.write(data)
# 리스트를 문자열로 변환하여 저장
save_to_file(output_file_path, ', '.join(all_nouns))
'IT기타' 카테고리의 다른 글
바이러스 또는 기타 사용자 동의 없이 설치된 소프트웨어가 있기 때문에 작업이 완료되지 않았습니다 (1) | 2024.07.14 |
---|---|
파이썬 - 특정폴더 안에 image 파일 PDF 한 파일에 붙여넣기. (0) | 2024.07.09 |
visual studio code 다중블록지정(선택 단어 다중선택, 세로 선택, 세로 블록, 블럭지정,여러행 블록) (1) | 2024.07.04 |
USB 디스크를 연결하면 포맷을 요구할 때 (0) | 2024.06.28 |
R studio 다운 (0) | 2024.06.13 |