본문 바로가기

TED에 등록된 최근 톡들 200개를 가지고 와서는 그들의 스크립트에서 가장많이 사용된 단어들을 추출하여 구글 스프레드 시트에 입력하는 예제입니다.


# -*- coding: utf-8 -*-

import json
import re
import gspread
import requests
import nltk
import sys
import codecs
import string
import time

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

from bs4 import BeautifulSoup
from oauth2client.client import SignedJwtAssertionCredentials

#nltk.download('punkt')
#nltk.download('stopwords')

#구글 콘솔에서 내려받은 json 파일을 지정한다
json_key = json.load(open('mykey.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'].encode(), scope)

TED_TALK_URL = 'http://www.ted.com/talks'
TED_URL = 'http://www.ted.com/'

SPREAD_SHEET_NAME = "TEST"

#총 200개의 TED 스크립트를 가지고 온다.
ALLCOUNT = 200

#TED 사이트의 페이지 (페이지당 36개의 TALK이 리스트업된다)
MAX_PAGE = 100

#4초 단위로 스크립트를 읽는다. 너무 빠르면 봇으로 간주되어 접속이 안된다 ㅋ
TIME_SLEEP = 4

punctuations = list(string.punctuation)
default_stopwords = set(nltk.corpus.stopwords.words('english'))

#엑셀의 첫번째 시트를 연다
def openExcel():
	gc = gspread.authorize(credentials)
	worksheet = gc.open(SPREAD_SHEET_NAME).sheet1	
	return worksheet


#해당 url로 부터 html tag를 획득한다
def get_soup(url):	
	source_code = requests.get(url)
	plain_text = source_code.text
	soup = BeautifulSoup(plain_text, 'lxml')
	return soup

#스크립트를 가지고 와서 문장이 포함하는 단어들을 리스트에 담는다
def script_reader(url):	
	curl = TED_URL + url + '/transcript?language=en'

	soup = get_soup(curl)

	words = []

	for spans in soup.find_all('span', class_="talk-transcript__fragment"):	
		words += word_tokenize(spans.text)

	# Remove single-character tokens (mostly punctuation)
	words = [word for word in words if len(word) > 1]

	# Remove numbers
	words = [word for word in words if not word.isnumeric()]

	# Lowercase all words (default_stopwords are lowercase too)
	words = [word.lower() for word in words]

	# Remove stopwords
	words = [word for word in words if word not in default_stopwords]

	# Remove punctuation
	words = [word for word in words if word not in punctuations]

	print(" + " + str(len(words)))	
	return words


#단어와 빈도수가 기록된 리스트를 엑셀에 쓴다
def writeListToExcel(words):	
	wks = openExcel()								
	wks.add_rows(len(words))

	cell_list = wks.range('A1:B%d' % len(words))

	idx = 0
	for word, frequency in words:
		cell_list[idx].value = word
		idx += 1
		cell_list[idx].value = frequency
		idx += 1
	            	
	wks.update_cells(cell_list)	
	print("done")

#최근에 등록된 톡들의 스크립트들을 가지고 온다				
def get_latest_ted(url):
	wholewords = []
	talk = 0

	# 36 scripts / page
	for page in range(1,MAX_PAGE):
		realurl = url + "?page=" + str(page)
		soup = get_soup(realurl)

		for h4 in soup.find_all('h4', class_="h9 m5"):				
			ted_talks_url = h4.a.get('href')			
			wholewords += script_reader(ted_talks_url)

			talk += 1

			print(str(page) + " page: " + str(talk) + " scripts are analyzed")	
			time.sleep(TIME_SLEEP)

			if talk >= ALLCOUNT:
				print("ALL = " + str(len(wholewords)) + " words")	
				en = nltk.FreqDist(wholewords)
				writeListToExcel(en.most_common(100))
				return

	en = nltk.FreqDist(wholewords)
	writeListToExcel(en.most_common(100))

get_latest_ted(TED_TALK_URL)





번호 제목 날짜 조회 수
공지 [TIP] 자작 운영체제 AiRPOS 소스를 공개합니다. 2026.07.04 11281
공지 [TIP] PYTHON 에서 "UnicodeDecodeError: 'cp949' codec can't decode byte 0xe2 in position 6987: illegal multibyte sequence" 오류 날때... [52] 2016.02.20 264647
공지 [펌] ARM GCC Inline Assembler Cookbook 2006.08.18 56611
공지 [TIP] R에서 페이스북 페이지 정보 크롤링 하기 [6] 2017.02.11 38663
150 [TIP] 파이선에서 AWS Lambda로 만든 Restful API 호출하기 (How to call AWS Lambda Restful API from Python) 2018.01.23 2734
149 [TIP] 파이선에서 서브프로세스를 실행시키고 출력되는 내용을 얻어오기 2018.01.22 12616
148 [TIP] 아두이노에서 AWS Lambda로 제작한 Restful API 호출하기 (The way how to call AWS Lambda Restful API from Arduino) 2018.01.18 2417
147 [TIP] 파이선에서 Redis 이벤트 받기 2017.10.12 1967
146 [TIP] 파이선에서 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position ... 오류 해결 방법 2017.09.29 3350
145 [TIP] The function size must be used with a prefix when a default namespace is not specified 오류 해결하기 2017.08.02 4308
144 [TIP] 페이스북 개인 담벼락의 좋아요수 크롤링하기 2017.07.15 2479
143 [TIP] 자바스크립트와 PHP코드간에 암호화 통신하기 (Encrypt with Javascript, Decrypt with PHP) [2] 2017.03.16 6090
142 [TIP] GUNMAN의 영화 점수 테이블을 이용한 딥러닝 예제 2017.02.15 3150
141 [TIP] R에서 페이스북 페이지 정보 크롤링 하기 [6] 2017.02.11 38663
140 [TIP] 네이버 영화 정보와 전문가 평점 얻어오기 2017.02.10 8643
139 [TIP] 네이버 오픈 API를 로컬 PC에서 호출하기 2017.02.01 4366
138 [TIP] php로 기상청에서 제공하는 기상정보 API 호출하기 2017.01.17 10660
137 [TIP] node 에서 Basic authentication 인증과 함께 http, https 요청하기 2016.09.01 2626
136 [TIP] node의 lambda-local 테스트 팁 2016.08.19 1870
135 [TIP] 데이터를 Node에서 암호화하고 PHP에서 복호화 하기 2016.08.19 2028
134 [TIP] Docker상의 Syntaxnet 결과 포맷을 수정하기 2016.08.07 3048
133 [TIP] SyntaxNet을 Windows에서 실행하기 [1] 2016.05.25 2001
132 [TIP] TensorFlow를 윈도우에서 사용하기 (A way to use TensorFlow on Windows) [3] 2016.04.16 23437
» [TIP] 파이선으로 TED에서 가장많이 사용된 단어들 줄세우기 2016.04.03 2609