【问题标题】:How to find all words that start with an uppercase letter using Python Regex [duplicate]如何使用Python Regex查找所有以大写字母开头的单词[重复]
【发布时间】:2021-04-24 04:37:11
【问题描述】:

下面是从文件中查找所有大写单词并将它们添加到列表中的代码,我该如何更改它以便只将以大写开头的单词添加到列表中。

import re

matches = []
regex = r"\b[A-Z]\w*"
filename = r'C:\Users\Documents\romeo.txt'
with open(filename, 'r') as f:
    for line in f:
        matches += re.findall(regex, line)
print(matches)

文件:

Hello, How are YOU

输出:

[Hello,How]

你不应该被包含在输出中。

【问题讨论】:

    标签: python-3.x regex file python-re findall


    【解决方案1】:

    \w 匹配大小写字母以及数字和下划线。如果您只想匹配小写字母,请按如下方式指定:

    regex = r"\b[A-Z][a-z]*\b"
    text = 'Hello, How are YOU'
    re.findall(pattern, text) # ['Hello', 'How']
    

    查看documentation 中的 Python 正则表达式语法以了解其他选项。

    【讨论】:

    • 行得通,谢谢。
    猜你喜欢
    • 2022-11-23
    • 2021-07-18
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    相关资源
    最近更新 更多