如何使用 Python 正则表达式查找首字母大写的所有单词

How to find all words with first letter as upper case using Python Regex

我需要找到文件中所有以大写字母开头的单词,我尝试了下面的代码,但它 returns 是一个空字符串。

import os
import re

matches = []

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

文件:

Hi, How are You?

输出:

[Hi,How,You]

你可以使用

import os, re

matches = []
filename = r'C:\Users\Documents\romeo.txt'
with open(filename, 'r') as f:
    for line in f:
        matches.extend([x for x in re.findall(r'\w+', line) if x[0].isupper()])
print(matches)

我们的想法是用一个简单的 \w+ 正则表达式提取所有单词,并只将那些以大写字母开头的单词添加到最终的 matches 列表中。

参见Python demo

注意:如果你只想匹配字母词使用r'\b[^\W\d_]+\b'正则表达式。

这种方法是 Unicode 友好的,也就是说,任何首字母大写的 Unicode 单词都会被找到。

:

Is there a way to limit this to only words that start with an upper case letter and not all uppercase words

您可以将之前的代码扩展为

[x for x in re.findall(r'\w+', line) if x[0].isupper() and not x.isupper()]

参见 this Python demo"Hi, How ARE You?" 产生 ['Hi', 'How', 'You']

或者,要避免在输出中出现 CaMeL 词,请使用

matches.extend([x for x in re.findall(r'\w+', line) if x[0].isupper() and all(i.islower() for i in x[1:])])

参见 this Python demo,其中 all(i.islower() for i in x[1:]) 确保第一个字母之后的所有字母均为小写。

完全正则表达式方法

您可以使用支持 Unicode 属性 和 POSIX 字符 类、\p{Lu}/\p{Ll} 和 [=22 的 PyPi 正则表达式模块=]/[:lower:]。所以,解决方案看起来像

import regex
text = "Hi, How ARE You?"
# Word starting with an uppercase letter:
print( regex.findall(r'\b\p{Lu}\p{L}*\b', text) )
## => ['Hi', 'How', 'ARE', 'You']
# Word starting with an uppercase letter but not ALLCAPS:
print( regex.findall(r'\b\p{Lu}\p{Ll}*\b', text) )
## => ['Hi', 'How', 'You']

参见 Python demo online 其中

  • \b - 单词边界
  • \p{Lu} - 任何大写字母[=7​​1=]
  • \p{L}* - 任意零个或多个字母[=7​​1=]
  • \p{Ll}* - 任意零个或多个小写字母[=7​​1=]

您可以使用单词边界代替锚 ^$

\b[A-Z]\w*

Regex demo

请注意,如果您使用 matches.append,您将一个项目添加到列表中,然后 re.findall returns 一个列表,这将为您提供一个列表列表。

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)

输出

['Hi', 'How', 'You']

如果左边应该有一个空白边界,你也可以使用

(?<!\S)[A-Z]\w*

Regex demo


如果您不想使用 \w 匹配仅包含大写字符的单词,您可以使用例如否定前瞻来断言不仅大写字符直到单词边界

\b[A-Z](?![A-Z]*\b)\w*
  • \b 防止部分匹配的单词边界
  • [A-Z] 匹配大写字符 A-Z
  • (?![A-Z]*\b) 否定前瞻,不仅断言大写字符后跟单词边界
  • \w* 匹配可选的单词字符

Regex demo


要匹配以大写字符开头且不包含更多大写字符的单词:

\b[A-Z][^\WA-Z]*\b
  • \b一个单词边界
  • [A-Z] 匹配大写字符 A-Z
  • [^\WA-Z]* 可选择匹配不带字符 A-Z 的单词字符
  • \b一个单词边界

Regex demo