上个月,我试图标记文本并创建一个单词,以查看哪个单词经常出现。今天,我想在具有相同代码的相同数据集中再次执行此操作。它仍然有效,但是结果不同,显然今天的结果是错误的,因为出现单词的频率大大降低。
这是我的代码:
from nltk.tokenize import sent_tokenize, word_tokenize
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
from nltk.stem import WordNetLemmatizer
import nltk
from collections import Counter
sent = nltk.word_tokenize(str(df.description))
lower_token = [t.lower() for t in sent]
alpha = [t for t in lower_token if t.isalpha()]
stop_word = [t for t in alpha if t not in ENGLISH_STOP_WORDS]
k = WordNetLemmatizer()
lemma = [k.lemmatize(t) for t in stop_word]
bow = Counter(lemma)
print(bow.most_common(20))
Here is a sample of my dataset
此数据集来自Kaggle,名称为“葡萄酒评论”。
欢迎使用StackOverflow。
可能有两个原因导致您的问题。
1)可能是您修改了数据集。为此,我将检查数据集,看看是否对数据本身进行了任何更改。因为您的代码可以在其他示例中使用,并且由于没有随机元素,所以每天都不会更改。
2)第二个问题可能是您在此行中调用数据框列时对df.description
的使用:
sent = nltk.word_tokenize(str(df.description))
您将获得截断的输出。查看df.description
的类型,它是Series
对象。
我创建了另一个示例,如下所示:
from nltk.tokenize import word_tokenize
import pandas as pd
df = pd.DataFrame({'description' : ['The OP is asking a question and I referred him to the Minimum Verifible Example page which states: When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. This is referred to by community members as creating a minimal, reproducible example (reprex), a minimal, complete and verifiable example (mcve), or a minimal, workable example (mwe). Regardless of how it\'s communicated to you, it boils down to ensuring your code that reproduces the problem follows the following guidelines:']})
print(df.description)
0 The OP is asking a question and I referred him...
Name: description, dtype: object
如上所述,它被截断了,不是description
列中的全文。
我对您的代码的建议是研究这一行代码,并找到另一种方式:
sent = nltk.word_tokenize(str(df.description))
请注意,您在代码中使用的方法将在您正在处理的数据中包括索引号(据我理解,您已按isalpha
进行了过滤。)以及此Name: description, dtype: object
。
一种方法是使用map
处理您的数据。一个例子是:
pd.set_option('display.max_colwidth', -1)
df['tokenized'] = df['description'].map(str).map(nltk.word_tokenize)
也要针对其他操作执行此操作。一种简单的方法是构建一个预处理函数,在数据帧上应用所有(要使用的)预处理操作。
我希望这会有所帮助。