从python中的列表中删除单词 [英] Removing words from list in python
本文介绍了从python中的列表中删除单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表"abc"(字符串),我试图从列表"abc"中删除列表"stop"中存在的某些单词以及abc中存在的所有数字.
I have a list 'abc' (strings) and I am trying to remove some words present in list 'stop' from the list 'abc' and all the digits present in abc.
abc=[ 'issues in performance 421',
'how are you doing',
'hey my name is abc, 143 what is your name',
'attention pleased',
'compliance installed 234']
stop=['attention', 'installed']
我正在使用列表推导将其删除,但是下面的这段代码无法删除该单词.
I am using list comprehension to remove it but this below code is not able to remove that word.
new_word=[word for word in abc if word not in stop ]
结果:(注意词仍然存在.)
Result:(attention word is still present.)
['issues in performance',
'how are you doing',
'hey my name is abc, what is your name',
'attention pleased',
'compliance installed']
所需的输出:
['issues in performance',
'how are you doing',
'hey my name is abc, what is your name',
'pleased',
'compliance']
谢谢
推荐答案
这是一个解决方案,它使用带有 re.sub
方法的简单正则表达式.此解决方案还删除了数字.
Here is a solution, using simple regular expression with the re.sub
method. This solution removes numbers as well.
import re
abc=[ 'issues in performance 421',
'how are you doing',
'hey my name is abc, 143 what is your name',
'attention pleased',
'compliance installed 234']
stop=['attention\s+', 'installed\s+', '[0-9]']
[(lambda x: re.sub(r'|'.join(stop), '', x))(x) for x in abc]
'Output':
['issues in performance ',
'how are you doing',
'hey my name is abc, what is your name',
'pleased',
'compliance ']
这篇关于从python中的列表中删除单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文