簡體   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