gpt4 book ai didi

python - 标题大小写的正则表达式 - Python

转载 作者:行者123 更新时间:2023-11-28 21:10:19 26 4
gpt4 key购买 nike

我需要找到 2 个连续的标题词的组合。

到目前为止,这是我的代码,

text='Hi my name is Moh Shai and This Is a Python Code with Regex and Needs Some Expertise'

rex=r'[A-Z][a-z]+\s+[A-Z][a-z]+'

re.findall(rex,text)

这给了我,

['Moh Shai', 'This Is', 'Python Code', 'Needs Some']

但是,我需要所有的组合。类似的东西,

['Moh Shai', 'This Is', 'Python Code', 'Needs Some','Some Expertise']

有人可以帮忙吗?

最佳答案

您可以将正则表达式前瞻与 re.finditer 函数结合使用以获得所需的结果:

import re

text='Hi my name is Moh Shai and This Is a Python Code with Regex and Needs Some Expertise'
rex=r'(?=([A-Z][a-z]+\s+[A-Z][a-z]+))'

matches = re.finditer(rex,text)
results = [match.group(1) for match in matches]

现在结果将包含您需要的信息:

>>> results
['Moh Shai', 'This Is', 'Python Code', 'Needs Some', 'Some Expertise']

编辑:就其值(value)而言,您甚至不需要 finditer 函数。您可以将底部的两行替换为上一行 re.findall(rex,text) 以获得相同的效果。

关于python - 标题大小写的正则表达式 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36731216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com