从列表中删除自定义词 - Python

Removing Custom-Defined Words from List - Python

我有一个数据框列,如下所示:

我正在考虑删除特殊字符。我希望附加标签(在列表列表中),以便我可以将该列附加到现有的 df。

这就是我收集了这么多,但似乎没有用。特别是正则表达式让我非常痛苦,因为它总是 returns“预期的字符串或类似字节的对象”。

df = pd.read_csv('flickr_tags_participation_inequality_omit.csv')
#df.dropna(inplace=True) and tokenise
tokens = df["tags"].astype(str).apply(nltk.word_tokenize)

filter_words = ['.',',',':',';','?','@','-','...','!','=', 'edinburgh', 'ecosse', 'écosse', 'scotland']
filtered = [i for i in tokens if i not in filter_words]
#filtered = [re.sub("[.,!?:;-=...@#_]", '', w) for w in tokens]
#the above line didn't work


tokenised_tags= []
for i in filtered:
    tokenised_tags.append(i) #this turns the single lists of tags into lists of lists
print(tokenised_tags)

以上代码没有删除自定义停用词。

非常感谢任何帮助!谢谢!

您需要使用

df['filtered'] = df['tags'].apply(lambda x: [t for t in nltk.word_tokenize(x) if t not in filter_words])

请注意,nltk.word_tokenize(x) 输出一个字符串列表,因此您可以对其应用规则列表理解。