从充满句子的数据框中删除字母分组和单词列表

2024-04-27 22:50:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧df,其中包含未清理的文本字符串

                             phrase
 0           the quick brown br fox
 1   jack and jill went up the hill

我还有一个单词和字母分组的列表,我想remove称为remove,如下所示:

['br', and]

在本例中,我希望得到以下输出:

                         phrase
 0          the quick brown fox
 1   jack jill went up the hill

请注意,“brown”中的br不是作为一个较大单词的一部分保留在df中,但是“br”本身被删除了

我试过:

df['phrase']=[re.sub(r"\b%remove\b", "", sent) for sent in df['phrase']]

但不能让它正常工作。有人能告诉我怎么做吗

谢谢


Tags: andthebrdfquick单词removejack
2条回答

我觉得它可以随着replace下降

s=[r'\b'+x+r'\b' for x in L]

df.phrase.str.replace('|'.join(s),'')
Out[176]: 
0           the quick brown  fox
1    jack  jill went up the hill
Name: phrase, dtype: object

split使用嵌套列表理解,通过in使用tes成员身份,并将拆分的值连接回:

L = ['br', 'and']

df['phrase']=[' '.join(x for x in sent.split() if x not in L) for sent in df['phrase']]
print (df)
                       phrase
0         the quick brown fox
1  jack jill went up the hill

相关问题 更多 >