假设以下数据框中有一列名为<;游戏>;:
df:
game
0 juegos blue
1 juego red
2 juegos yellow
我想从以下停止词列表中删除这些词:
stopWords = ['juego','juegos']
期望的结果是:
df:
game
0 blue
1 red
2 yellow
我试过:
df['game'] = df['game'].str.replace("|".join(stopWords ), " ")
该函数可以工作,但它会从条目“juegos”中删除“juego”,而不使用“s”:
df:
game
0 s blue
1 red
2 s yellow
有没有一种方法只有在完全匹配的情况下才能删除单词
Python字符串替换将不起作用,但正则表达式模块将起作用。您需要在字符串中添加一些标记,以使正则表达式查找完整的单词。例如,您可能知道它是一个完整的单词,因为它后面跟一个句点
.
、逗号,
、任何类型的空格\s
、或一个尾行$
\b
是单词边界的正则表达式模式(我从this other good answer偷了
\b
。)保留旧代码以防您感兴趣。这一步还可以直接删除匹配单词后的空格、逗号或句点,这不是您所要求的,但可能很有用
只需使用DataFrame.replace()即可
假设stop'words'以单词边界
\b
结尾相关问题 更多 >
编程相关推荐