Python创建Emoji-字母替换字典时遇NameError报错的解决方法
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 theNameError). - Added
from collections import Counterto make theCounterclass 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

