gpt4 book ai didi

python - 在 pandas 数据帧的所有行上迭代 nltk.tokenize

转载 作者:行者123 更新时间:2023-12-01 07:11:48 24 4
gpt4 key购买 nike

感谢您对这个看似愚蠢的问题的帮助。我已将 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矩阵放入数据帧中不是一个好主意。但理解和可视化模型的各个步骤可能很有用。

关于python - 在 pandas 数据帧的所有行上迭代 nltk.tokenize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58175521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com