Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何使用Python正则表达式查找以大写字母开头的所有单词_Python 3.x_Regex_File_Re_Findall - Fatal编程技术网

Python 3.x 如何使用Python正则表达式查找以大写字母开头的所有单词

Python 3.x 如何使用Python正则表达式查找以大写字母开头的所有单词,python-3.x,regex,file,re,findall,Python 3.x,Regex,File,Re,Findall,下面是从文件中查找所有大写单词并将其添加到列表中的代码,如何更改此代码,以便仅将以大写开头的单词添加到列表中 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) pri

下面是从文件中查找所有大写单词并将其添加到列表中的代码,如何更改此代码,以便仅将以大写开头的单词添加到列表中

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]

输出中不应包含您。

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

regex=r“\b[A-Z][A-Z]*\b”
text='你好,你好吗'
关于findall(模式、文本)#[“你好”、“怎么样”]

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

很好,谢谢。
[Hello,How]