📜  单词模式python代码示例

📅  最后修改于: 2022-03-11 14:47:07.156000             🧑  作者: Mango

代码示例1
import string

def word_to_pattern(word):
    # Stores actual-letter to pattern-placeholder mapping
    mapping = {}

    # ZYXW... so we cap pop letters starting with A from the end
    available_pattern_letters = list(string.ascii_uppercase)[::-1]

    pattern = []
    for letter in word.upper():
        if letter not in string.ascii_uppercase:
            # for punctuation etc
            pattern.append(letter)
            continue
        if letter not in mapping:
            # new letter we haven't seen yet in this word
            mapping[letter] = available_pattern_letters.pop()
        pattern.append(mapping[letter])
    return pattern.join("")