python - 在 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)
这看起来应该可以工作,但仍然只返回第一行中的单词。
解决方案
我认为使用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 矩阵转换为数据框不是一个好主意。但理解和可视化模型的各个步骤可能很有用。
推荐阅读
- c# - 如何获取 XElement 的内部文本?
- javascript - 如何关闭面具
- reactjs - React Amplify/Datastore-无法删除要删除的记录
- arrays - 提高 bash 中将文件列与数组进行比较的性能
- javascript - 如何提前一天从当天到一周填充html元素?
- javascript - 尝试循环引导行,使用 DOM 在每个行中添加 3 个 col-4
- python - 如何与子进程交互和使用应用程序的属性
- javascript - React.js 创建一个可以左右移动对象的div
- python - Tkinter Python gui登录不起作用,我该如何解决?
- python - 日期时间字符串解析不适用于语言环境全名