如何在python中删除字符串的特定部分

问题描述 投票:0回答:1

我尝试删除具有与旁边相同字词相同模式的特定字词。

doc = [“超级男人好天气”,“赌徒好车”,“钢铁侠真棒汤”]

我想删除“超人”,“赌徒”,“钢铁侠”。这些字符串具有相同的单词“ man”,我想同时删除同一单词“ man”前面的单词。

我尝试了此代码,但失败了。 T ^ T对于文档中的字符串:prep = re.sub('。* man =','',string)

python text preprocessor
1个回答
0
投票

不是一种优雅的方法。却达到目的。

doc = ["super man good weather", "bet man nice car", "iron man awesome soup", "this doesn't contain that keyword"]

doc = [string.split("man")[1].strip()  if "man" in string else string for string in doc]

print(doc)

输出

['good weather', 'nice car', 'awesome soup', "this doesn't contain that keyword"]
© www.soinside.com 2019 - 2024. All rights reserved.