gpt4 book ai didi

Python 正则表达式提取第一个大写单词或第一个和第二个单词(如果两者都大写)

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:37 25 4
gpt4 key购买 nike

我实现的当前正则表达式公式只能提取给定字符串的前两个大写单词。如果第二个单词没有大写,我希望能够只提取字符串中的第一个单词。

这里有一些例子:

s = 'Smith John went to ss for Jones.'
s = 'Jones, Greg went to 2b for Smith.'
s = 'Doe went to ss for Jones.'

本质上,我只希望正则表达式输出以下内容:

'Smith John'
'Jones, Greg'
'Doe'

我目前的正则表达式公式如下,但它不会捕获 Doe 示例:

new = re.findall(r'([A-Z][\w-]*(?:\s+[A-Z][\w-]*)+)', s)

最佳答案

正则表达式太过分了。 str.isupper() 运行良好:

In [11]: def getName(s):
...: first, second = s.split()[:2]
...: if first[0].isupper():
...: if second[0].isupper():
...: return ' '.join([first, second])
...: return first
...:

这给出:

In [12]: getName('Smith John went to ss for Jones.')
Out[12]: 'Smith John'

In [13]: getName('Jones, Greg went to 2b for Smith.')
Out[13]: 'Jones, Greg'

In [14]: getName('Doe went to ss for Jones.')
Out[14]: 'Doe'

添加一些检查,这样当您的字符串只有一个单词时它就不会出错,您就可以开始了。


如果你执意要使用正则表达式,你可以使用这样的模式:

In [36]: pattern = re.compile(r'([A-Z].*? ){1,2}')

In [37]: pattern.match('Smith John went to ss for Jones.').group(0).rstrip()
Out[37]: 'Smith John'

In [38]: pattern.match('Doe went to ss for Jones.').group(0).rstrip()
Out[38]: 'Doe'

r'([A-Z].*? ){1,2}' 将匹配第一个,也可以匹配第二个,如果它们是大写的话。

关于Python 正则表达式提取第一个大写单词或第一个和第二个单词(如果两者都大写),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44960996/

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