【发布时间】:2021-06-29 01:46:59
【问题描述】:
我正在尝试从 python pandas 数据框中的一组字符串(文本)中删除常用词列表。数据框看起来像这样
['Item', 'Label', 'Comment']
我已经删除了停用词,但我做了一个词云,还有一些更常见的词我想删除以更好地了解这个问题。
这是我当前的工作代码,效果不错但还不够好
# This recieves a sentence 1 at a time
# Use a loop if you want to process a dataset or a lambda
def nlp_preprocess(text, stopwords, lemmatizer, wordnet_map):
# Remove punctuation
text = re.sub('[^a-zA-Z]', ' ', text)
# Remove tags
text=re.sub("</?.*?>"," <> ",text)
# Remove special characters and digits
text=re.sub("(\\d|\\W)+"," ",text)
# Remove stop words like and is a and the
text = " ".join([word for word in text.split() if word not in stopwords])
# Find base word for all words in the sentence
pos_tagged_text = nltk.pos_tag(text.split())
text = " ".join([lemmatizer.lemmatize(word, wordnet_map.get(pos[0], wordnet.NOUN)) for word, pos in pos_tagged_text])
return text
def full_nlp_text_process(df, pandas_parms, stopwords, lemmatizer, wordnet_map):
data = preprocess_dataframe(df, pandas_params)
nlp_data = data.copy()
nlp_data["ProComment"] = nlp_data['Comment'].apply(lambda x: nlp_preprocess(x, stopword, lemmatizer, wordnet_map))
return data, nlp_data
我知道我想要类似的东西,但我不知道我应该如何把它放在那里以删除单词以及我应该把它放在哪里(即在文本处理或数据帧过程中)\
fdist2 = nltk.FreqDist(text)
most_list = fdist2.most_common(10)
# Somewhere else
for t in text:
if t in most_list: text.remove(t)
【问题讨论】:
-
请参考one
-
如果您知道如何删除
stopwords,然后创建包含要删除的单词的列表并像使用stopwords一样使用它 -
在 Python 中更好地使用您想要保留的单词创建新列表,而不是从您在
for-loop 中使用的列表中删除单词。与您删除stopwords的方式相同 - 您创建了包含您想要保留的单词的新列表。 -
我的问题是我应该把它放在哪里。因为我的清理代码逐行工作,可能无法获得整个文档的所有常用词。但话又说回来,我不是 100% 确定这是否正确,因为这是一个假设