使用列表推导替换字符串

Mik*_*Sam 6 python string list-comprehension list

是否可以使用列表推导完成此示例:

a = ['test', 'smth']
b = ['test Lorem ipsum dolor sit amet',
     'consectetur adipiscing elit',
     'test Nulla lectus ligula',
     'imperdiet at porttitor quis',
     'smth commodo eget tortor', 
     'Orci varius natoque penatibus et magnis dis parturient montes']


for s in a:
    b = [el.replace(s,'') for el in b]
Run Code Online (Sandbox Code Playgroud)

我要从句子列表中删除特定的单词。我可以使用循环来实现,但是我想可以使用一些单行解决方案来实现。

我尝试了类似的东西:

b = [[el.replace(s,'') for el in b] for s in a ]
Run Code Online (Sandbox Code Playgroud)

但这是错误的


我得到了很多优质的答案,但是现在我有了更多的麻烦:如果我想使用单词组合怎么办?

a = ['test', 'smth commodo']
Run Code Online (Sandbox Code Playgroud)

谢谢您的回答!我对所有解决方案进行了速度测试,结果如下:我这样做意味着要进行100次计算(除了最后一次计算,等待时间太长了)。

                      b=10 a=2   |  b=9000 a=2 | b=9000 a=100 | b=45k a=500
---------------------------------+-------------+--------------+---------------
COLDSPEED solution:   0.0000206  |  0.0311071  |  0.0943433   |  4.5012770
Jean Fabre solution:  0.0000871  |  0.1722340  |  0.2635452   |  5.2981001
Jpp solution:         0.0000212  |  0.0474531  |  0.0464369   |  0.2450547
Ajax solution:        0.0000334  |  0.0303891  |  0.5262040   | 11.6994496
Daniel solution:      0.0000167  |  0.0162156  |  0.1301132   |  6.9071504
Kasramvd solution:    0.0000120  |  0.0084146  |  0.1704623   |  7.5648351
Run Code Online (Sandbox Code Playgroud)

我们可以看到Jpp解决方案是我们不能使用的最快的BUT解决方案-这是所有其他解决方案中无法解决单词组合问题的一种解决方案(我已经写过他,希望他能改善回答!)。所以看起来像@c ??? s ???? 的解决方案是大数据集上最快的。

cs9*_*s95 4

你所拥有的没有任何问题,但如果你想清理一下并且性能并不重要,那么编译一个正则表达式模式并sub在循环内调用。

>>> import re
>>> p = re.compile(r'\b({})\b'.format('|'.join(a)))
>>> [p.sub('', text).strip() for text in b]
Run Code Online (Sandbox Code Playgroud)

['Lorem ipsum dolor sit amet',
 'consectetur adipiscing elit',
 'Nulla lectus ligula',
 'imperdiet at porttitor quis',
 'commodo eget tortor',
 'Orci varius natoque penatibus et magnis dis parturient montes'
]
Run Code Online (Sandbox Code Playgroud)

详细信息
您的模式将如下所示:

\b    # word-boundary - remove if you also want to replace substrings
(
test  # word 1
|     # regex OR pipe
smth  # word 2 ... you get the picture
)
\b    # end with another word boundary - again, remove for substr replacement
Run Code Online (Sandbox Code Playgroud)

这是编译后的正则表达式模式匹配器:

>>> p
re.compile(r'\b(test|smth)\b', re.UNICODE)
Run Code Online (Sandbox Code Playgroud)

另一个考虑因素是您的替换字符串本身是否包含可由正则表达式引擎以不同方式解释的字符 - 而不是被视为文字 - 这些是正则表达式元字符,您可以在构建模式时转义它们。这是使用re.escape.

p = re.compile(r'\b({})\b'.format(
    '|'.join([re.escape(word) for word in a]))
)
Run Code Online (Sandbox Code Playgroud)

当然,请记住,随着数据量的增加和替换的增多,正则表达式和字符串替换都会变得乏味。考虑使用更适合大型操作的东西,例如flashtext.