繁体   English   中英

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

[英]how to remove specific parts of string in python

我试图删除具有相同模式的特定单词,即旁边的特定单词。

doc = ["super man good weather", "bet man nice car", "iron man awesome soup"]

我想删除'super man''bet man''iron man' 这些字符串具有相同的单词“man”,我想同时删除相同单词“man”前面的单词。

我试过这个,但失败了。

for string in doc:
    prep = re.sub('.* man =', '', string)

不是优雅的方式。 但服务于目的。

doc = ["super man good weather", "bet man nice car", "iron man awesome soup", "a manned mission to mars"]

keyword = " man " # to make sure that you don't remove words that contain man as substring

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

print(doc)

Output

['good weather', 'nice car', 'awesome soup', 'a manned mission to mars']

此处查看此操作

基于正则表达式的解决方案

import re
doc = ["man super man good weather", "a bet man nice car", "iron man awesome man soup", "a manned mission to mars"]
doc = [re.sub('\w+ man ', '', string).strip() for string in doc]
print(doc)

Output

['man good weather', 'a nice car', 'soup', 'a manned mission to mars']

此处查看实际操作

试试这个..应该使用re

[re.sub('[a-zA-Z]+\s{1}man', '', txt).strip() for txt in doc]

我的方法是

re.sub('\w+ man ', '', t)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM