用Python创建替换字典

2024-09-28 19:01:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个密码要破译

我得到了一个阿尔贝斯,不是用字母,而是用表情符号。第一个表情符号是A,第二个是B,第三个是C等:

🎅 = A
🤶 = B
❄ = C
⛄ = D

我的整个表情符号alpabeth如下所示:

alphabet_emoji = "🎅🤶❄⛄🎄🎁🕯🌟✨🔥🥣🎶🎆👼🦌🛷"

现在我想使用字典将每个表情符号映射到它的字母。我尝试了以下代码:

replacement_dictionary[emoji] = str(letter);

然而,这给了我一个错误:

NameError: name 'replacement_dictionary' is not defined

我的全部代码:

# Input
alphabet_emoji = "🎅🤶❄⛄🎄🎁🕯🌟✨🔥🥣🎶🎆👼🦌🛷"
alphabet_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'


# Connect emoji to alpabet
print("Length: " + str(len(alphabet_emoji)))
print("Emoji\tUnicode\tOccurrence\tLetter")
counter = Counter(alphabet_emoji)
x = 0
for emoji in alphabet_emoji:
    unicode = f'U+{ord(emoji):X}'
    occurrence = counter[emoji]
    letter = alphabet_uppercase[x]
    print(emoji + "\t" + unicode + "\t" + str(occurrence) + "\t" + letter)

    # Add to dictionary
    replacement_dictionary[emoji] = str(letter);


    # Counter
    x=x+1

解决Hobo先生评论问题的代码

# Input
alphabet_emoji = "🎅🤶❄⛄🎄🎁🕯🌟✨🔥🥣🎶🎆👼🦌🛷"
alphabet_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'


# Connect emoji to alpabet
print("\nHexmax A")
print("Length: " + str(len(alphabet_emoji)))
print("Emoji\tUnicode\tOccurrence\tLetter")
counter = Counter(alphabet_emoji)
replacement_dictionary = dict()
x = 0
for emoji in alphabet_emoji:
    unicode = f'U+{ord(emoji):X}'
    occurrence = counter[emoji]
    letter = alphabet_uppercase[x]
    print(emoji + "\t" + unicode + "\t" + str(occurrence) + "\t" + letter)

    # Add to dictionary
    replacement_dictionary[emoji] = str(letter);

    x = x+1

Tags: to代码dictionarycounterunicodeprintemoji表情符号
2条回答

您从未/没有定义变量replacement_dictionary,但您可以访问它。也许这是正确的代码

# Input
alphabet_emoji = "🎅🤶❄⛄🎄🎁🕯🌟✨🔥🥣🎶🎆👼🦌🛷"
alphabet_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'


# Connect emoji to alpabet
print("Length: " + str(len(alphabet_emoji)))
print("Emoji\tUnicode\tOccurrence\tLetter")

counter = Counter(alphabet_emoji)

# Fixed here
replacement_dictionary = {}

# Loop(s)
for emoji in alphabet_emoji:
    unicode = f'U+{ord(emoji):X}'
    occurrence = counter[emoji]
    letter = alphabet_uppercase[x]
    
    print(emoji + "\t" + unicode + "\t" + str(occurrence) + "\t" + letter)
    
    # Add to dictionary
    replacement_dictionary[emoji] = str(letter);

或者如果您想使用**而不是replacement_dictionary[...],下面是代码

# Input
alphabet_emoji = "🎅🤶❄⛄🎄🎁🕯🌟✨🔥🥣🎶🎆👼🦌🛷"
alphabet_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'


# Connect emoji to alpabet
print("Length: " + str(len(alphabet_emoji)))
print("Emoji\tUnicode\tOccurrence\tLetter")

counter = Counter(alphabet_emoji)

# Fixed here
replacement_dictionary = {}

# Loop(s)
for emoji in alphabet_emoji:
    unicode = f'U+{ord(emoji):X}'
    occurrence = counter[emoji]
    letter = alphabet_uppercase[x]
    
    print(emoji + "\t" + unicode + "\t" + str(occurrence) + "\t" + letter)
    
    # Add to dictionary
    replacement_dictionary = {emoji: str(letter), **replacement_dictionary};

首先定义词典

your_dict = {}

your_dict = dict()

相关问题 更多 >