在列表中查找单词,然后删除该单词和列中的任何其他尾随单词

2024-09-27 07:33:20 发布

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

如何查找列表中的单词并在找到单词后删除其他单词?你知道吗

例如:

remove_words = ['stack', 'over', 'flow']

输入:

0    abc test test stack yxz
1    cde test12 over ste
2    def123 flow test123
3    yup over 4562

要从列表中查找单词请删除熊猫数据框列中的单词列表,然后删除这些单词和后面的任何单词。你知道吗

结果:

0    abc test test
1    cde test12 
2    def123
3    yup

Tags: test列表stackflow单词removeoverwords
3条回答

对regex OR使用^{}by all joined values by |并选择第一个listby str[0]

remove_words = ['stack', 'over', 'flow']

#for more general solution with word boundary
pat = r'\b{}\b'.format('|'.join(remove_words))
df['col'] = df['col'].str.split(pat, n=1).str[0]
print (df)
              col
0  abc test test 
1     cde test12 
2         def123 
3            yup 

我没有用pandas dataframe编写,但是concert在任何语言中都应该是相同的,只要循环遍历所有单词并使用一个带空字符串的replace方法即可。你知道吗

第一步是检查输入中是否有值,如果没有,可以返回整个输入

if "stack" or "over" or "flow" not in input: 
    return input

现在是拆卸部分。我认为最好的方法是循环输入数组中的每个值(我假设它是一个数组)并调用str_replace

相关问题 更多 >

    热门问题