从字符串中提取所有大写单词

问题描述 投票:0回答:4

在像这个"A B c de F G A"这样的字符串中,我想获得以下列表:["A B", "F G A"]。这意味着,我需要获得大写单词的所有序列。

我试过这样的事情:

text = "A B c de F G A"
result = []
for i, word in enumerate(text.split()):
    if word[0].isupper():
        s = ""
        while word[0].isupper():

            s += word
            i += 1
            word = text[i]

        result.append(s)

但它产生了以下输出:['A', 'BB', 'F', 'G', 'A']

我想这是因为你不能通过增加i来跳过列表元素。如何避免这种情况并获得正确的输出?

python string list uppercase
4个回答
7
投票

你可以使用itertools.groupby

import itertools
s = "A B c de F G A"
new_s = [' '.join(b) for a, b in itertools.groupby(s.split(), key=str.isupper) if a]

输出:

['A B', 'F G A']

1
投票

您可以使用re.split将字符串与正则表达式分开。

import re

def get_upper_sequences(s):
    return re.split(r'\s+[a-z][a-z\s]*', s)

>>> get_upper_sequences( "A B c de F G A")
['A B', 'F G A']

0
投票

这是没有itertoolsre的解决方案:

def findTitles(text):
    filtered = " ".join([x if x.istitle() else " " for x in text.split()])
    return [y.strip() for y in filtered.split("  ") if y]

print(findTitles(text="A B c de F G A"))
#['A B', 'F G A']

print(findTitles(text="A Bbb c de F G A"))
#['A Bbb', 'F G A']

0
投票

以下示例将从字符串中提取所有大写单词:

string="A B c de F G A"

import re
[val for val in re.split('[a-z]*',string.strip()) if val != " "]
© www.soinside.com 2019 - 2024. All rights reserved.