Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬으로 웹 페이지를 크롤링하고 가장 많이 쓰인 단어 추출하기

이번 글에서는 파이썬을 활용해 웹 페이지를 크롤링한 뒤, 페이지에 등장하는 단어의 빈도를 계산하고 가장 많이 사용된 단어들을 추출하는 프로그램을 만들어 보겠습니다.

먼저 requestsBeautifulSoup 모듈을 사용해 간단한 웹 크롤러를 구현합니다. 이 두 모듈로 웹 페이지의 데이터를 가져오고, 추출한 텍스트는 리스트에 저장한 후 후속 처리를 진행합니다.

사용되는 주요 모듈

  • requests : 지정한 URL의 웹 페이지 소스 코드를 가져옵니다.
  • BeautifulSoup : HTML 문서를 파싱하여 원하는 태그와 텍스트를 손쉽게 추출합니다.
  • collections.Counter : 단어별 개수를 세고, 상위 N개의 최빈 항목을 간편하게 구할 수 있습니다.

예제 코드

import requests
from bs4 import BeautifulSoup
import operator
from collections import Counter

def my_start(url):
   my_wordlist = []
   my_source_code = requests.get(url).text
   my_soup = BeautifulSoup(my_source_code, 'html.parser')
   for each_text in my_soup.findAll('div', {'class':'entry-content'}):
      content = each_text.text
      words = content.lower().split()
      for each_word in words:
         my_wordlist.append(each_word)
      clean_wordlist(my_wordlist)

# 불필요한 특수 문자를 제거하는 함수
def clean_wordlist(wordlist):
   clean_list =[]
   for word in wordlist:
      symbols = '!@#$%^&*()_-+={[}]|\;:"<>?/., '
      for i in range (0, len(symbols)):
         word = word.replace(symbols[i], '')
      if len(word) > 0:
         clean_list.append(word)
   create_dictionary(clean_list)

def create_dictionary(clean_list):
   word_count = {}
   for word in clean_list:
      if word in word_count:
         word_count[word] += 1
      else:
         word_count[word] = 1
   c = Counter(word_count)
   # 가장 많이 등장한 요소를 반환
   top = c.most_common(10)
   print(top)

# 실행 코드
if __name__ == '__main__':
   my_start("https://www.tutorialspoint.com/python3/python_overview.htm/")

코드 동작 원리

  1. my_start(url) : URL에서 HTML 소스를 받아온 뒤, entry-content 클래스를 가진 div 태그 내부의 텍스트를 추출하고, 모든 문자를 소문자로 변환한 후 단어 단위로 분리해 리스트에 저장합니다.
  2. clean_wordlist() : 리스트에 담긴 단어에서 특수 기호를 제거하여 깔끔한 단어 목록을 만듭니다.
  3. create_dictionary() : 각 단어의 등장 횟수를 딕셔너리에 저장한 후, Countermost_common(10) 메서드를 통해 최다 빈출 단어 10개를 출력합니다.

출력 결과

프로그램을 실행하면 대상 웹 페이지에서 가장 많이 등장한 단어 10개가 빈도수와 함께 튜플 형태로 출력됩니다.

파이썬으로 웹 페이지를 크롤링하고 가장 많이 쓰인 단어 추출하기