시작하기무료로 시작하기

간단한 Twitter 텍스트 분석

이제 트윗 DataFrame이 준비되었으니, 약간의 텍스트 분석을 해서 'clinton', 'trump', 'sanders', 'cruz'라는 단어가 포함된 트윗이 각각 몇 개인지 세어 보겠습니다. 연습 문제 전 코드에서 아래 함수 word_in_text()를 정의해 두었으며, 이 함수는 첫 번째 인자(단어)가 두 번째 인자(트윗) 안에 등장하는지를 알려줍니다.

import re

def word_in_text(word, text):
    word = word.lower()
    text = text.lower()
    match = re.search(word, text)

    if match:
        return True
    return False

이제 DataFrame의 각 행을 순회하면서, 각 키워드가 포함된 트윗 수를 계산해 보세요! 각 후보에 대한 객체의 값은 0으로 초기화되어 있습니다.

이 연습은 강의의 일부입니다

Intermediate Importing Data in Python

강의 보기

연습 안내

  • for index, row in df.iterrows(): 루프 안에서, 현재 코드는 'Clinton'을 언급한 트윗(텍스트 행)을 만날 때마다 clinton의 값을 1씩 증가시킵니다. 같은 방식으로 trump, sanders, cruz에 대해서도 코드가 동작하도록 완성하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# Initialize list to store tweet counts
[clinton, trump, sanders, cruz] = [0, 0, 0, 0]

# Iterate through df, counting the number of tweets in which
# each candidate is mentioned
for index, row in df.iterrows():
    clinton += word_in_text('clinton', row['text'])
    trump += word_in_text(____, ____)
    sanders += word_in_text(____, ____)
    cruz += word_in_text(____, ____)
코드 편집 및 실행