如何在Pandas数据帧上为Twitter数据应用NLTK word_tokenize库?

时间:2017-05-25 06:21:49

标签: python pandas twitter nltk tokenize

这是我用于Twitter语义分析的代码: -

import pandas as pd
import datetime
import numpy as np
import re
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer

df=pd.read_csv('twitDB.csv',header=None, 
sep=',',error_bad_lines=False,encoding='utf-8')

hula=df[[0,1,2,3]]
hula=hula.fillna(0)
hula['tweet'] = hula[0].astype(str) 
+hula[1].astype(str)+hula[2].astype(str)+hula[3].astype(str) 
hula["tweet"]=hula.tweet.str.lower()

ho=hula["tweet"]
ho = ho.replace('\s+', ' ', regex=True) 
ho=ho.replace('\.+', '.', regex=True)
special_char_list = [':', ';', '?', '}', ')', '{', '(']
for special_char in special_char_list:
ho=ho.replace(special_char, '')
print(ho)

ho = ho.replace('((www\.[\s]+)|(https?://[^\s]+))','URL',regex=True)
ho =ho.replace(r'#([^\s]+)', r'\1', regex=True)
ho =ho.replace('\'"',regex=True)

lem = WordNetLemmatizer()
stem = PorterStemmer()
fg=stem.stem(a)

eng_stopwords = stopwords.words('english') 
ho = ho.to_frame(name=None)
a=ho.to_string(buf=None, columns=None, col_space=None, header=True, 
index=True, na_rep='NaN', formatters=None, float_format=None, 
sparsify=False, index_names=True, justify=None, line_width=None, 
max_rows=None, max_cols=None, show_dimensions=False)
wordList = word_tokenize(fg)                                     
wordList = [word for word in wordList if word not in eng_stopwords]  
print (wordList)

输入,即: -

                                              tweet
0     1495596971.6034188::automotive auto ebc greens...
1     1495596972.330948::new free stock photo of cit...

以这种格式获取输出(wordList): -

tweet
 0
1495596971.6034188
:
:automotive
auto

我只希望以行格式输出行。我该怎么做? 如果您有更好的Twitter语义分析代码,请与我分享。

1 个答案:

答案 0 :(得分:12)

简而言之:

df['Text'].apply(word_tokenize)

或者,如果要添加另一列来存储标记化的字符串列表:

df['tokenized_text'] = df['Text'].apply(word_tokenize) 

有专门为twitter文本编写的标记符,请参阅http://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.casual

使用nltk.tokenize.TweetTokenizer

from nltk.tokenize import TweetTokenizer
tt = TweetTokenizer()
df['Text'].apply(tt.tokenize)

类似于: