You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python创建Emoji-字母替换字典时遇NameError报错的解决方法

Fixing the NameError: name 'replacement_dictionary' is not defined in Your Emoji-to-Letter Mapping Code

Hey there! The error you’re hitting is super straightforward: you’re trying to assign values to a dictionary (replacement_dictionary) that never got created in the first place. Python has no idea what that variable is until you initialize it, hence the NameError.

Let’s break down the problem in your original code

The critical issue is this line:

replacement_dictionary[emoji] = str(letter);

Before this line runs, you never declared replacement_dictionary as an empty dictionary. Python can’t find a variable with that name, so it throws an error. Also, don’t forget you need to import Counter from the collections module—your original code would’ve hit another error without that import!

Here’s the corrected working code

I’ve added the missing dictionary initialization, fixed the import, and cleaned up formatting for readability:

from collections import Counter

# Input
alphabet_emoji = "虜❄⛄✨北歷"
alphabet_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

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

counter = Counter(alphabet_emoji)
replacement_dictionary = dict()  # This line fixes the NameError!
x = 0

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

Key fixes explained

  • Added replacement_dictionary = dict() to create an empty dictionary before adding key-value pairs (this resolves the NameError).
  • Added from collections import Counter to make the Counter class available (it’s not part of Python’s base namespace).
  • Swapped the print statement to use an f-string for cleaner, more maintainable code.
  • Removed the unnecessary semicolon at the end of the dictionary assignment line (semicolons aren’t required in Python unless you’re putting multiple statements on one line).

Now your code will successfully build the emoji-to-letter mapping dictionary without errors, and print out each emoji’s Unicode value, occurrence count, and corresponding letter as expected.

内容的提问来源于stack exchange,提问作者Europa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:50:48