【问题标题】:Regex - Extract substrings starting with capitalized letter in a list, with french special symbols正则表达式 - 提取列表中以大写字母开头的子字符串,带有法语特殊符号
【发布时间】:2021-07-15 17:46:24
【问题描述】:

我有一组像这样的法语字符串:

text = "Français Langues bantoues Presse écrite Gabon Particularité linguistique"

我想将大写字母开头的子串提取到一个列表中,如下:

list = ["Français", "Langues bantoues", "Presse écrite", "Gabon", "Particularité linguistique"]

我确实尝试过类似的方法,但它不包含以下单词,并且由于法语符号而停止。

import re
pattern = "([A-Z][a-z]+)"

text = "Français Langues bantoues Presse écrite Gabon Particularité linguistique"

list = re.findall(pattern, text)
list

输出 ['Fran', 'Langues', 'Presse', 'Gabon', 'Particularit']

不幸的是,我没有设法在论坛上找到解决方案。

【问题讨论】:

    标签: python regex french


    【解决方案1】:

    由于这与特定的 Unicode 字符处理有关,我建议使用 PyPi regex module(使用 pip install regex 安装)然后您可以使用

    import regex
    text = "Français Langues bantoues Presse écrite Gabon Particularité linguistique"
    matches = regex.split(r'(?!\A)\b(?=\p{Lu})', text)
    print( list(map(lambda x: x.strip(), matches)) )
    # => ['Français', 'Langues bantoues', 'Presse écrite', 'Gabon', 'Particularité linguistique']
    

    请参阅online Python demoregex demo详情

    • (?!\A) - 字符串开头以外的位置
    • \b - 单词边界
    • (?=\p{Lu}) - 要求下一个字符为 Unicode 大写字母的正向前瞻。

    请注意,map(lambda x: x.strip(), matches) 用于从结果块中去除多余的空白。

    也可以使用re 做到这一点

    import re, sys
    text = "Français Langues bantoues Presse écrite Gabon Particularité linguistique"
    pLu = '[{}]'.format("".join([chr(i) for i in range(sys.maxunicode) if chr(i).isupper()]))
    matches = re.split(fr'(?!\A)\b(?={pLu})', text)
    print( list(map(lambda x: x.strip(), matches)) )
    # => ['Français', 'Langues bantoues', 'Presse écrite', 'Gabon', 'Particularité linguistique']
    

    请参阅this Python demo,但请记住,支持的 Unicode 大写字母数量因版本而异,使用 PyPi 正则表达式模块使其更加一致。

    【讨论】:

    • 您的代码就像一个魅力,感谢您非常详细的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    相关资源
    最近更新 更多