首页 > 解决方案 > 在 pandas 数据帧的所有行中迭代 nltk.tokenize

问题描述

感谢您对看似愚蠢的问题的帮助。我已经将一个 sqlite 表拉入了一个 pandas 数据框中,这样我就可以标记并计算一系列推文中单词的频率。

使用下面的代码,我可以为第一条推文生成这个。如何迭代整个表?

conn = sqlite3.connect("tweets.sqlite")
data = pd.read_sql_query("select tweet_text from tweets_new;", conn)

tokenizer=RegexpTokenizer(r'\w+')
tokens=tokenizer.tokenize(data['tweet_text'][0])

words = nltk.FreqDist(tokens)

unigram_df = pd.DataFrame(words.most_common(),
                             columns=["WORD","COUNT"])

unigram_df

当我将值更改为单行以外的任何值时,我收到以下错误:

TypeError: expected string or buffer

我知道还有其他方法可以做到这一点,但我需要按照这些思路来做,因为我打算接下来如何使用输出。感谢您的任何帮助,您可以提供!

我努力了:

%%time

tokenizer = RegexpTokenizer(r'\w+')  

print "Cleaning the tweets...\n"
for i in xrange(0,len(df)):
    if( (i+1)%1000000 == 0 ):  
        tokens=tokenizer.tokenize(df['tweet_text'][i])
        words = nltk.FreqDist(tokens)

这看起来应该可以工作,但仍然只返回第一行中的单词。

标签: pythonpandasnltktokenize

解决方案


我认为使用CountVectorizer可以更简洁地解决您的问题。我给你举个例子。给定以下输入:

from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd 

corpus_tweets = [['I love pizza and hambuerger'],['I love apple and chips'], ['The pen is on the table!!']]
df = pd.DataFrame(corpus_tweets, columns=['tweet_text'])

您可以使用以下几行创建您的词袋模板:

count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(df.tweet_text)

您可以打印获得的词汇表:

count_vect.vocabulary_
# ouutput: {'love': 5, 'pizza': 8, 'and': 0, 'hambuerger': 3, 'apple': 1, 'chips': 2, 'the': 10, 'pen': 7, 'is': 4, 'on': 6, 'table': 9}

并获取带有字数的数据框:

df_count = pd.DataFrame(X_train_counts.todense(), columns=count_vect.get_feature_names())

   and  apple  chips  hambuerger  is  love  on  pen  pizza  table  the
0    1      0      0           1   0     1   0    0      1      0    0
1    1      1      1           0   0     1   0    0      0      0    0
2    0      0      0           0   1     0   1    1      0      1    2

如果它对您有用,您可以将计数的数据框与语料库的数据框合并:

pd.concat([df, df_count],  axis=1)

                    tweet_text  and  apple  chips  hambuerger  is  love  on  \
0  I love pizza and hambuerger    1      0      0           1   0     1   0   
1       I love apple and chips    1      1      1           0   0     1   0   
2    The pen is on the table!!    0      0      0           0   1     0   1   

   pen  pizza  table  the  
0    0      1      0    0  
1    0      0      0    0  
2    1      0      1    2  

如果要获取包含<word, count>每个文档的对的字典,此时您需要做的就是:

dict_count = df_count.T.to_dict()

{0: {'and': 1,
  'apple': 0,
  'chips': 0,
  'hambuerger': 1,
  'is': 0,
  'love': 1,
  'on': 0,
  'pen': 0,
  'pizza': 1,
  'table': 0,
  'the': 0},
 1: {'and': 1,
  'apple': 1,
  'chips': 1,
  'hambuerger': 0,
  'is': 0,
  'love': 1,
  'on': 0,
  'pen': 0,
  'pizza': 0,
  'table': 0,
  'the': 0},
 2: {'and': 0,
  'apple': 0,
  'chips': 0,
  'hambuerger': 0,
  'is': 1,
  'love': 0,
  'on': 1,
  'pen': 1,
  'pizza': 0,
  'table': 1,
  'the': 2}}

注意:将X_train_counts稀疏numpy 矩阵转换为数据框不是一个好主意。但理解和可视化模型的各个步骤可能很有用。


推荐阅读