【问题标题】:How to remove words starting with capital letter in a list of strings using re.sub in python如何在python中使用re.sub删除字符串列表中以大写字母开头的单词
【发布时间】:2020-06-24 07:59:02
【问题描述】:

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

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

我想得到以下输出,删除的单词没有多余的空格:

['am','is going to']

【问题讨论】:

  • 您的代码在哪里遇到问题,问题在哪里?学习一门编程语言会犯很多错误——否则每次出现新问题时你都会问。

标签: python regex list word python-re


【解决方案1】:

你可以试试这个:

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)

输出:

['am', 'is going to']

【讨论】:

    【解决方案2】:

    你可以试试

    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])
    

    输出

    ['am', 'is going to']
    

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

    【讨论】:

    • 欢迎您。如果您可以标记答案并投票,我们将很高兴为您提供帮助。
    • 谁能告诉下面的正则表达式使用什么例如-我正在尝试为这个列表写一个正则表达式:data = [“我是约翰。乔要去美国”,“ Cathy 也会陪他去美国。”] 我想删除所有以大写字母开头的单词,但它不应该检查每个句子的第一个单词,即它不应该检查 I、Jo 和 Cathy。输出应该是 Output-["I am. Jo is going to", "Cathy will also follow him to."] 谢谢。
    猜你喜欢
    • 2016-08-24
    • 2021-09-25
    • 2021-03-12
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2022-11-23
    相关资源
    最近更新 更多