[Python] Get all Cyrillic characters with any type of accent/diacritics [closed]

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I need to identify any Cyrillic (and only Cyrillic) with diacritics (all types). The code I provided works quite well except it doesn't catch combined characters (first group in the test string, е́ doesn't have accent displayed for some reason).

    import unicodedata

    # Define Cyrillic Unicode ranges
    cyrillic_ranges = [
    (0x0400, 0x04FF), # Cyrillic
    (0x0500, 0x052F), # Cyrillic Supplement
    (0x2DE0, 0x2DFF), # Cyrillic Extended-A
    (0xA640, 0xA69F), # Cyrillic Extended-B
    (0x1C80, 0x1C8F), # Cyrillic Extended-C
    (0x1E030, 0x1E08F), # Cyrillic Extended-D
    (0x1D2B, 0x1D2B), # Phonetic Extension (ᴫ)
    (0x1D78, 0x1D78) # Phonetic Extension (ᵸ)
    ]

    diacritics = {
    0x0300, 0x0301, 0x0303, 0x0304, 0x0306, 0x0307, 0x0308, 0x030A,
    0x030B, 0x030C, 0x030F, 0x0311, 0x0323, 0x0328, 0x0331, 0x033E
    }

    def is_cyrillic_with_diacritic(char):
    char_code = ord(char)
    if any(start <= char_code <= end for start, end in cyrillic_ranges):
    normalized = unicodedata.normalize('NFD', char)
    return any(unicodedata.combining(c) for c in normalized)
    return False

    # Example text
    text = "а́е́Ы́ ё́ќѓЀЃЌЍѐѓќѝ нЧǎȟáỳýćé" #1st group not caught, 2nd group caught, 3rd not caught and shouldn't be caught (latin or cyrillic without diacritics)

    # Extract Cyrillic characters with diacritics
    filtered_chars = [char for char in text if is_cyrillic_with_diacritic(char)]

    # Print the result
    print("Cyrillic letters with diacritics:", ''.join(filtered_chars))

    Continue reading...

Compartilhe esta Página