본문 바로가기
IT/Scraping

자연어 처리하기: 데이터 요약

by Cyber_ 2025. 2. 20.

만약 텍스트 컨텐츠를 n-그램, 즉 단어 n개로 구성된 구절로 나누어 빈도수가 높은 단어 혹은 문장을 추출해 요약한다고 합시다.

 

우선 operator 모듈에 들어 있는 파이썬 정렬 함수를 이용하여 n-그램을 찾고 정렬하는 코드를 구성한다고 합시다.

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import string
from collections import Counter

def cleanSentence(sentence):
    sentence = sentence.split(' ')
    sentence = [word.strip(string.punctuation + string.whitespace)
        for word in sentence]
    sentence = [word for word in sentence if len(word) > 1
        or (word.lower() == 'a' or word.lower() == 'i')]
    return sentence

def cleanInput(content):
    content = content.upper()
    content = re.sub('\n|[[\d+\]]', ' ', content)
    content = bytes(content, "UTF-8")
    content = content.decode("ascii", "ignore")
    sentences = content.split(', ')
    return [cleanSentence(sentence) for sentence in sentences]

def getNgramsFromSentence(content, n):
    output = []
    for i in range(len(content)-n+1):
        output.append(content[i:i+n]
    return output

def getNgrams(content, n):
    content = cleanInput(content)
    ngrams = Counter()
    ngrmas_list = []
    for sentence in content:
        newNgrams = [' '.join(ngrmas) for ngram in getNgrams in getNgrmasFromSentence(sentence,n)]
        ngrams_list.extend(newNgrams)
        ngrmas.update(newNgrams)
    return(ngrams)

speech = 'http://pythonscraping.com/files/inaugurationSpeech.txt'
content = str(urlopen(speech).read(), 'utf-8')
ngrams = getNgrams(content, 2)
print(ngrams)

위 코드를 통한 출력 결과에는 of the, in the, to the 와 같은 필요 없는 단어들이 있습니다. 이런 필요 없는 단어들은 브리검영 대학교의 언아학 교수인 마크 데이브스는, 4억 5천만개 이상의 단어로 구성된 현대 미국 영어자료(http://corpus.byu.edu/coca/)

관리하고 있습니다.

 

English-Corpora: COCA

 

www.english-corpora.org

 

 

이 중에서 가장 많이 사용된 단어 5천개의 리스트는 무료로 제공되며, 이 정도면 가장 널리 쓰이는 2-그램을 걸래는 기본 필터로 충분합니다.

  def getNgramsFromSentence(content, n):
      output = []
      for i in range(len(content)-n+1):
          if not isCommon(content[i:i+n]):
              output.append(content[i:i+n])
      return output

  def isCommon(ngram):
      commonWords = ['THE', 'BE', 'AND', 'OF', 'A', 'IN', 'TO', 'HAVE',
                    'IT', 'I', 'THAT', 'FOR', 'YOU', 'HE', 'WITH', 'ON',
                    'DO', 'SAY', 'THIS', 'THEY', 'IS', 'AN', 'AT', 'BUT',
                    'WE','HIS', 'FROM', 'THAT', 'NOT', 'BY', 'SHE', 'OR',
                    'AS', 'WHAT', 'GO', 'THEIR', 'CAN', 'WHO', 'GET', 'IF',
                    'WOULD', 'HER', 'ALL', 'MY', 'MAKE', 'ABOUT', 'KNOW',
                    'WILL', 'AS', 'UP', 'ONE', 'TIME', 'HAS', 'BEEN', 'THERE',
                    'YEAR', 'SO', 'THINK', 'WHEN', 'WHICH', 'THEM', 'SOME',
                    'ME', 'PEOPLE', 'TAKE', 'OUT', 'INTO', 'JUST', 'SEE',
                    'HIM', 'YOUR', 'COME', 'COULD', 'NOW', 'THAN', 'LIKE',
                    'OTHER', 'HOW', 'THEN', 'ITS', 'OUR', 'TWO', 'MORE',
                    'THESE', 'WANT', 'WAY', 'LOOK', 'FIRST', 'ALSO', 'NEW',
                    'BECUASE', 'DAY', 'MORE', 'USE', 'NO', 'MAN', 'FIND',
                    'HERE', 'THING', 'GIVE', 'MANY', 'WELL']
    for word in ngram:
        if word in commonWords:
            return true
    return False

 

위와 같은 단어 추출을 통해 핵심 주제는 유추할 수 있습니다. 이제 텍스트 요약은 어떻게 해야할까요?

 

한 가지 방법은 자주 쓰인 n-그램 각각에 대해 그 구절이 쓰인 첫 번째 문장을 검색하는 것입니다. 첫 문장인만큼 본문 전체에 대한 만족할 만한 개관이 될 거라고 짐작할 수 있습니다.

 

n-그램에서 핵심 단어들이 2-그램일지, 3-그램일지, 4-그램일지이는 모르는 일입니다. 그래서 우선 가장 많이 등장하는 n-그램이 포함된 문장을 찾는 방법이 있습니다. 이런 방법을 쓰면 찾아낸 문자의 길이가 꽤 길 가능성이 있는데, 문장 길이가 문제가 된다면 자주 등장하는 n-그램 비율이 가장 높은 문장을 찾거나 기타 자신만의 테크닉을 조작해 기준을 만들 수 있습니다.