【问题标题】:Python - Split a string but keep contiguous uppercase letters [duplicate]Python - 拆分字符串但保持连续的大写字母[重复]
【发布时间】:2020-11-11 10:36:27
【问题描述】:

我想将字符串拆分为大写字母分隔单词,但如果它包含连续的大写字母,请将其拆分为一个单词,直到最后一个字母之前(可能开始一个新单词..)

例如:

splitThreeWords -> [split, three, words]
SplitThreeWords -> [split, three, words]
ILOSummit -> [ILO, summit]

【问题讨论】:

  • 你怎么知道s属于summit?
  • 我不确定,但假设是这样。

标签: python string split


【解决方案1】:

将re.split 与捕获组一起使用(以保持拆分器模式)并过滤掉空块:

import re


def split_by_title_word(s):
    return [chunk for chunk in re.split(r"([A-Z][a-z]+)", s) if chunk]


print(split_by_title_word("splitThreeWords"))
print(split_by_title_word("SplitThreeWords"))
print(split_by_title_word("IOLSummit"))

输出

['split', 'Three', 'Words']
['Split', 'Three', 'Words']
['IOL', 'Summit']

模式[A-Z][a-z]+ 代表一个title 字。

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 2011-05-28
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    相关资源
    最近更新 更多