본문 바로가기
파이썬

텍스트 요약(Text Summarization )

by akasha.park 2023. 3. 28.

텍스트 요약(Text Summarization ) :

상대적으로 큰 원문을 핵심 내용만 간추려서 상대적으로 작은 요약문으로 변환하는 것

 


추출적 요약(extractive summarization) : 
원문에서 중요한 핵심 문장 또는 단어구를 몇 개 뽑아서 이들로 구성된 요약문을 만드는 방법
추출적 요약의 결과로 나온 요약문의 문장이나 단어구들은 전부 원문에 있는 문장들입니다. 
텍스트랭크(TextRank) 머신 러닝 알고리즘
https://summariz3.herokuapp.com/
요약된 문장은 원문에 이미 존재하는 문장이나 단어구로만 구성하므로 모델의 언어 표현 능력이 제한된다

 

 

추상적 요약(abstractive summarization) :
원문에 없던 문장이라도 핵심 문맥을 반영한 새로운 문장을 생성해서 원문을 요약하는 방법
인공 신경망 모델  seq2seq 지도 학습을 사용
추상적 요약을 인공 신경망으로 훈련하기 위해서는 '원문' 뿐만 아니라 '실제 요약문'이라는 레이블 데이터가 있어야 합니다.
데이터를 구성하는 것 자체가 하나의 부담입니다.




아마존 리뷰 데이터 약 56만개의 샘플 (Reviews.csv )
https://www.kaggle.com/snap/amazon-fine-food-reviews
 'Id', 'ProductId', 'UserId', 'ProfileName', 'HelpfulnessNumerator', 'HelpfulnessDenominator', 'Score', 'Time', 'Summary', 'Text' 10개의 열이 존재

//10만개의 샘플만 사용
data = pd.read_csv("Reviews.csv 파일의 경로", nrows = 100000)
print('전체 리뷰 개수 :',(len(data)))

//Text(원문)으로부터 Summary(요약)을 예측하도록 훈련
data = data[['Text','Summary']]
data.head()

//데이터 정제 - 중복 샘플 확인 후 제거
print('Text 열에서 중복을 배제한 유일한 샘플의 수 :', data['Text'].nunique())
print('Summary 열에서 중복을 배제한 유일한 샘플의 수 :', data['Summary'].nunique())
data.drop_duplicates(subset=['Text'], inplace=True)
print("전체 샘플수 :", len(data))

 

//데이터 정제 - Null 샘플이 존재하는지 확인   후 제거
print(data.isnull().sum())
data.dropna(axis=0, inplace=True)
print('전체 샘플수 :',(len(data)))

 

//동일한 의미를 가졌지만 스펠링이 다른 단어들을 정규화하기 위한 사전 생성
contractions = {"'cause": 'because',
 "I'd": 'I would',
 "I'd've": 'I would have',
 "I'll": 'I will',
 "I'll've": 'I will have',
 "I'm": 'I am',
 "I've": 'I have',
 "ain't": 'is not',
 "aren't": 'are not',
 "can't": 'cannot',
 "could've": 'could have',
 "couldn't": 'could not',
 "didn't": 'did not',
 "doesn't": 'does not',
 "don't": 'do not',
 "hadn't": 'had not',
 "hasn't": 'has not',
 "haven't": 'have not',
 "he'd": 'he would',
 "he'll": 'he will',
 "he's": 'he is',
 "here's": 'here is',
 "how'd": 'how did',
 "how'd'y": 'how do you',
 "how'll": 'how will',
 "how's": 'how is',
 "i'd": 'i would',
 "i'd've": 'i would have',
 "i'll": 'i will',
 "i'll've": 'i will have',
 "i'm": 'i am',
 "i've": 'i have',
 "isn't": 'is not',
 "it'd": 'it would',
 "it'd've": 'it would have',
 "it'll": 'it will',
 "it'll've": 'it will have',
 "it's": 'it is',
 "let's": 'let us',
 "ma'am": 'madam',
 "mayn't": 'may not',
 "might've": 'might have',
 "mightn't": 'might not',
 "mightn't've": 'might not have',
 "must've": 'must have',
 "mustn't": 'must not',
 "mustn't've": 'must not have',
 "needn't": 'need not',
 "needn't've": 'need not have',
 "o'clock": 'of the clock',
 "oughtn't": 'ought not',
 "oughtn't've": 'ought not have',
 "sha'n't": 'shall not',
 "shan't": 'shall not',
 "shan't've": 'shall not have',
 "she'd": 'she would',
 "she'd've": 'she would have',
 "she'll": 'she will',
 "she'll've": 'she will have',
 "she's": 'she is',
 "should've": 'should have',
 "shouldn't": 'should not',
 "shouldn't've": 'should not have',
 "so's": 'so as',
 "so've": 'so have',
 "that'd": 'that would',
 "that'd've": 'that would have',
 "that's": 'that is',
 "there'd": 'there would',
 "there'd've": 'there would have',
 "there's": 'there is',
 "they'd": 'they would',
 "they'd've": 'they would have',
 "they'll": 'they will',
 "they'll've": 'they will have',
 "they're": 'they are',
 "they've": 'they have',
 "this's": 'this is',
 "to've": 'to have',
 "wasn't": 'was not',
 "we'd": 'we would',
 "we'd've": 'we would have',
 "we'll": 'we will',
 "we'll've": 'we will have',
 "we're": 'we are',
 "we've": 'we have',
 "weren't": 'were not',
 "what'll": 'what will',
 "what'll've": 'what will have',
 "what're": 'what are',
 "what's": 'what is',
 "what've": 'what have',
 "when's": 'when is',
 "when've": 'when have',
 "where'd": 'where did',
 "where's": 'where is',
 "where've": 'where have',
 "who'll": 'who will',
 "who'll've": 'who will have',
 "who's": 'who is',
 "who've": 'who have',
 "why's": 'why is',
 "why've": 'why have',
 "will've": 'will have',
 "won't": 'will not',
 "won't've": 'will not have',
 "would've": 'would have',
 "wouldn't": 'would not',
 "wouldn't've": 'would not have',
 "y'all": 'you all',
 "y'all'd": 'you all would',
 "y'all'd've": 'you all would have',
 "y'all're": 'you all are',
 "y'all've": 'you all have',
 "you'd": 'you would',
 "you'd've": 'you would have',
 "you'll": 'you will',
 "you'll've": 'you will have',
 "you're": 'you are',
 "you've": 'you have'}

//단어 정규화와 불용어 제거
def preprocess_sentence(sentence, remove_stopwords = True):
    sentence = sentence.lower()                 # 텍스트 소문자화
    # <br />, <a href = ...> 등의 html 태그 제거
    sentence = BeautifulSoup(sentence, "lxml").text    
   # 괄호로 닫힌 문자열  제거   
    sentence = re.sub(r'\([^)]*\)', '', sentence)   
    sentence = re.sub('"','', sentence)       # 쌍따옴표 " 제거
    sentence = ' '.join([contractions[t] if t in contractions else t for t in sentence.split(" ")])    # 약어 정규화
    sentence = re.sub(r"'s\b","",sentence) # 소유격 제거
    # 영어 외 문자(숫자, 특수문자 등) 공백으로 변환
    sentence = re.sub("[^a-zA-Z]", " ", sentence) 
    # m이 3개 이상이면 2개로 변경. Ex) ummmmmmm yeah -> umm yeah   
    sentence = re.sub('[m]{2,}', 'mm', sentence) 

    # 불용어 제거 (Text)
    if remove_stopwords:
        tokens = ' '.join(word for word in sentence.split() if not word in stop_words if len(word) > 1)
    # 불용어 미제거 (Summary)
    else:
        tokens = ' '.join(word for word in sentence.split() if len(word) > 1)
    return tokens

 

 

 

시퀀스-투-시퀀스(Sequences-to-Sequence, seq2seq) 

 

'파이썬' 카테고리의 다른 글

자연어 처리를 위한 환경 구성, 배경 지식  (0) 2023.04.26
ChatGPT  (0) 2023.04.07
함수 정의 Coding연습  (0) 2023.03.23
제어문, 반복문 Coding 연습 3  (0) 2023.03.23
제어문, 반복문 Coding 연습3  (0) 2023.03.23