Python 从用户提供的列表中删除停止字

Python 从用户提供的列表中删除停止字,python,pandas,dataframe,apply,stop-words,Python,Pandas,Dataframe,Apply,Stop Words,我有一个原始语料库,正在尝试用一个用户定义的停止词列表删除停止词。我编辑了nltk英语停止词文件。我的stopwords文件一定有问题吧 以下是原始语料库的输入: 这是我的密码: #my own custom stopwords list stoplist="/User/dlhoffman/nltk_data/corpora/stopwords/english" #filter out stopwords raw_corpus['constructed_recipe'] = raw_corpus

我有一个原始语料库,正在尝试用一个用户定义的停止词列表删除停止词。我编辑了nltk英语停止词文件。我的stopwords文件一定有问题吧

以下是原始语料库的输入:

这是我的密码:

#my own custom stopwords list
stoplist="/User/dlhoffman/nltk_data/corpora/stopwords/english"
#filter out stopwords
raw_corpus['constructed_recipe'] = raw_corpus['constructed_recipe'].apply(lambda x: [item for item in x if 
item not in stoplist])
#running the code below verifies empty dataframe
#raw_corpus['constructed_recipe'] = raw_corpus['constructed_recipe'].apply(lambda x: [])
这是结果——显然不是我想要的!怎么了

使用生成器表达式应该可以:

import pandas as pd
import re

df = pd.DataFrame([['this is the first test string'],
                   ['this is yet another test'],
                   ['this is a third test item'],
                   ['this is the final test string']],
                  columns=['String'])

replace_set = {'this', 'is'}

df['String'] = df['String'].str.split(' ').apply(lambda x: ' '.join(k for k in x if k not in replace_set))

# df
#                     String
# 0    the first test string
# 1         yet another test
# 2        a third test item
# 3    the final test string
解释

split按空格分割单词,返回一系列列表,每个列表项一个单词。 pd.Series.apply接受lambda匿名函数作为输入,有效地将函数应用于循环中序列中的每个项。 如果k不在replace_集合中,则x中k的生成器表达式k将k的每个值作为受if条件约束的可替换项返回。 “”.join用于生成器表达式,以从生成的单词形成字符串。
这是有道理的。我向一位同事展示了上面的代码,他说如果我先标记,它就会工作。符合事实的我确实做了标记化,但后来。这就是问题所在吗?应用方法无法知道单词是什么?你上面的方法可以解决这个问题,对吗?这是另一种方法。您的尝试是在字符串中一次循环一个字母:[如果项目不在停止列表中,则在x中的项目对应项目]。迭代字符串时,您将分别查看每个元素。相反,您需要在字符串中查找停止字,并用空字符串替换它们。re.sub在功能上做到了这一点。@profhoff实际上,apply方法没有单词的概念,它只是对列中的每个字符串应用一些逻辑。这种方法的缺点是你可能会得到双空格,但是如果这是一个问题的话,这很容易纠正。啊!谢谢你的快速帮助。还是不起作用看起来apply函数不理解我的每个标记都是一个单词,所以它从每个单词中提取stopwords。不确定如何解决:例如,weather weather sunrise创建一条状态消息facebook社交网络变成->['wer'、'wer'、'unr'、'ce'、'u'、'ege'、'fcebk'、'cl'、'newrk']