[python] 파이썬 웹 크롤링(8): 자연어 읽고 쓰기

업데이트:

파이썬 웹 크롤링(8): 자연어 읽고 쓰기

본 포스팅은 Web Scraping with Python by Ryan Mitchell을 참고하였습니다.

참고 링크

Chapter 8: 자연어 읽고 쓰기

지금까지는 잘 갖추어진 숫자나 값을 다루었지만 이번 단원에서는 영어에 대해 꽤 까다로운 작업을 해보겠습니다. 여러분이 구글 사이트에서 cute kitten이라고 검색했을 때 어떻게 이미지를 찾을까요? 이는 해당 이미지들이 제목이나 묘사에 cute kitten이라는 단어를 포함하기 때문에 알수 있는 것입니다. 하지만 핫도그는 어떻습니까? 핫도그는 hot dog인데 어떻게 동물 개가 나오지 않고 음식이 나오는 걸까요? 이는 통계에 기반한 결과를 보여주기 때문입니다.

물론 여러분이 이 사실을 몰라도 크롤링할 때 지장은 없을지 몰라도 알면 도움이 됩니다. 특히 머신러닝 분야에서는 더욱 도움이 됩니다. 예를 들어 Shazam 음악 서비스는 음악을 탐색할 때 오디오가 잡음을 포함하더라도 구분할 수 있습니다.

8.1 데이터 요약하기

챕터 7에서는, n개의 단어로 구성되어있는 텍스트 내용을 n-gram으로 분리했습니다. 이는 데이터 통계를 내는데 유용합니다. 이번에 살펴볼 데이터는 미국 9대 대통령의 연설 입니다. 연설문의 풀텍스트는 연설문 링크에서 확인할 수 있습니다. 아래코드는 연설문을 2-gram으로 나눠서 통계를 내는 코드입니다.

from bs4 import BeautifulSoup
import re
import string
import operator

def cleanInput(input):
  input = re.sub('\n+', " ", input).lower()
  input = re.sub('\[[0-9]*\]', "", input)
  input = re.sub(' +', " ", input)
  input = bytes(input, "UTF-8")
  input = input.decode("ascii", "ignore")
  cleanInput = []
  input = input.split(' ')
  for item in input:
    item = item.strip(string.punctuation)
    if len(item) > 1 or (item.lower() == 'a' or item.lower() == 'i'):
      cleanInput.append(item)
    return cleanInput

def ngrams(input, n):
  input = cleanInput(input)
  output = {}
  for i in range(len(input)-n+1):
    ngramTemp = " ".join(input[i:i+n])
    if ngramTemp not in output:
      output[ngramTemp] = 0
    output[ngramTemp] += 1
  return output

content = str(
      urlopen("http://pythonscraping.com/files/inaugurationSpeech.txt").read(),
      'utf-8')
      ngrams = ngrams(content, 2)
sortedNGrams = sorted(ngrams.items(), key = operator.itemgetter(1),
reverse=True)
print(sortedNGrams)

결과는 아래와 같습니다.

[('of the', 213), ('in the', 65), ('to the', 61), ('by the', 41), 
('the constitution', 34), ('of our', 29), ('to be', 26), 
('from the', 24), ('the people', 24), ('and the', 23), ('it is', 23), 
('that the', 23), ('of a', 22), ('of their', 19)

위와 같은 2-grams의 결과를 보면 의미있게 많이 사용된 단어는 “the constitution”이라는 것을 알 수 있습니다. 물론 “of the”나, “in the”, “to the”와 같은 단어도 많이 사용되었지만 딱히 의미있어보이지는 않습니다. 그렇면 어떻게 자동으로 원하지 않는 결과들을 지워낼까요?

운이 좋게도, 흥미있는 단어와 흥미없는 단어의 차이를 구분해내는 연구를 하는 사람들이 있었습니다. 이들은 450 million 단어를 수십년 동안 모았습니다. 그리고 5,000개의 가장 자주 사용하는 단어들을 정했습니다. 이 단어들은 2-grams에서 제거할수 있습니다.

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", "because",
    "day", "more", "use", "no", "man", "find", "here", "thing", "give",
    "many", "well"]
  for word in ngram:
    if word in commonWords:
      return True
  return False

이들은 다음과 같은 2-grams를 보여줍니다.

('united states', 10), ('executive department', 4), 
('general government', 4), ('called upon', 3), 
('government should', 3), ('whole country', 3), 
('mr jefferson', 3), ('chief magistrate', 3), 
('same causes', 3), ('legislative body', 3)

첫 두개의 단어를 보면 united states, executive department인데, 이는 대통령 취임 연설에 적절한 단어로 보입니다.

우리가 사용하는 단어들은 비교적 현대 단어라는 것을 기억하십시오. 만약 텍스트가 1841년에 만들어진 것이라면 적절하지 않을 수 있습니다.

8.2 마르코프 모형