python - 删除 pandas 数据集中的停用词
问题描述
我正在尝试删除 apadas 数据集中的停用词,其中每一行都有一个标记化的单词列表,单词列表的格式如下:
['Uno', ',', 'dos', 'One', ',', 'two', ',', 'tres', ',', 'quatro', 'Yes', ',', 'Wooly', 'Bully', 'Watch', 'it', 'now', ',', 'watch', 'it', 'Here', 'he', 'come', ',', 'here', 'he', 'come', 'Watch', 'it', 'now', ',', 'he', 'git', 'ya', 'Matty', 'told', 'Hattie', 'about', 'a', 'thing', 'she', 'saw', 'Had', 'two', 'big', 'horns', 'and', 'a', 'wooly', 'jaw', 'Wooly', 'Bully', ',', 'Wooly', 'Bully', ',', 'yes', 'drive', 'Wooly', 'Bully', ',', 'Wooly', 'Bully', ',', 'Wooly', 'Bully', 'Hattie', 'told', 'Matty', '``', 'Let', "'s", 'do', "n't", 'take', 'no', 'chance', 'Let', "'s", 'not', 'be', 'L-seven', ',', 'come', 'and', 'learn', 'to', 'dance', "''", 'Wooly', 'Bully', ',', 'Wooly', 'Bully', 'Wooly', 'Bully', ',', 'Wooly', 'Bully', ',', 'Wooly', 'Bully', 'Watch', 'it', 'now', ',', 'watch', 'it', ',', 'watch', 'it', ',', 'watch', 'it', 'Yeah', 'Yeah', ',', 'drive', ',', 'drive', ',', 'drive', 'Matty', 'told', 'Hattie', '``', 'That', "'s", 'the', 'thing', 'to', 'do', 'Get', 'you', 'someone', 'really', 'pull', 'the', 'wool', 'with', 'you', "''", 'Wooly', 'Bully', ',', 'Wooly', 'Bully', 'Wooly', 'Bully', ',', 'Wooly', 'Bully', ',', 'Wooly', 'Bully', 'Watch', 'it', 'now', ',', 'watch', 'it', ',', 'here', 'he', 'come', 'You', 'got', 'it', ',', 'you', 'got', 'it']
使用以下代码执行此操作。
ret = df['tokenized_lyric'].apply(lambda x: [item for item in x if item.lower() not in stops])
print(ret)
这使我得到如下列表
e0 [n, , , , n, e, , , w, , , r, e, , , ...
2165 [ , n, r, , , r, , r, , l, , p, r, , , ...
似乎删除了几乎所有字符。我如何让它只删除我设置的停用词?
解决方案
您正在使用列表推导迭代字符串的字符。相反,在 之后lower()
,使用拆分字符串split()
然后迭代工作令牌,如下所示 -
print([i for i in 'hi there']) #iterating over the characters
print([i for i in 'hi there'.split()]) #iterating over the words
['h', 'i', ' ', 't', 'h', 'e', 'r', 'e']
['hi', 'there']
试试这个 lambda 函数 -
s = 'Hello World And Underworld'
stops = ['and','or','the']
f = lambda x: [item for item in x.split() if item.lower() not in stops]
f(s)
['hello', 'world', 'underworld']
写你的代码,它会是 -
df['tokenized_lyric'].apply(lambda x: [item for item in x.split() if item.lower() not in stops])
推荐阅读
- vb.net - 将对象分组到新对象类
- reporting-services - 在 Ssrs 2019 中,如何解释 Subscriptions.InactiveFlags?
- python - 即使它是正确的,我也无法运行我的程序
- javascript - 如何在 Javascript 中创建一个设置的倒数计时器?
- bigbluebutton - BigBlueButton 和 Greenlight - 配置 TURN 服务器时 BigBlueButton 端点和密钥无效
- python - 如何将我的数据的所有标签添加到 matplotlib 图的 x 轴?
- node.js - 如何使用 AWS 批处理将文件从 S3 复制到 EFS?
- flutter - 如何在颤动中自定义点击效果(波纹)?
- c# - 使用遥测无线电时 serialport.DataToRead 增加
- c# - 如何为来自多个分页 api 的数据正确设置分页逻辑