繁体   English   中英

如何使用 python 中的 re.sub 删除字符串列表中以大写字母开头的单词

[英]How to remove words starting with capital letter in a list of strings using re.sub in python

我正在使用 Python 并且我想使用re.sub删除字符串列表中以大写字母开头的单词。 例如,给定以下列表:

l = ['I am John','John is going to US']

我想得到以下 output,删除的单词没有任何额外的空格:

['am','is going to']

你可以试试这个:

output = []
for sentence in l:
    output.append(" ".join([word for word in sentence.strip().split(" ") if not re.match(r"[A-Z]",word)]))
print(output)

output:

['am', 'is going to']

你可以试试

import re

l=['I am John','John is going to US']
print([re.sub(r"\s*[A-Z]\w*\s*", " ", i).strip() for i in l])

Output

['am', 'is going to']

这是一个正则表达式,它从给定字符串中删除以大写字母开头的所有单词,此外它将删除单词前后的所有空格。

暂无
暂无

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

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