首页 > 解决方案 > 当单词数小于 N 时,删除 pandas 数据框中的字符串行

问题描述

我正在为 NLP 分类任务预处理数据集,我想删除少于 3 个单词的句子,我尝试删除少于 3 个字母的单词的代码:

import re
text = "The quick brown fox jumps over the lazy dog."
# remove words between 1 and 3
shortword = re.compile(r'\W*\b\w{1,3}\b')
print(shortword.sub('', text))

如何在python中做到这一点?

标签: pythontextnlp

解决方案


使用 Pandas 数据框:

import pandas
text = {"header":["The quick fox","The quick fox brown jumps hight","The quick"]}
df = pandas.DataFrame(text)
df = df[df['header'].str.split().str.len().gt(2)]  
print(df)

上面的代码片段过滤了 'header' 列长度大于 2 个单词的数据帧。

有关 pandas 数据框的更多信息,请参阅https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html


推荐阅读