Python盲文转换:如何处理大写字母并添加前缀编码?
Hey there! Let's work through your two questions and get your braille converter working exactly how you need it.
1. Checking for Uppercase Keys in Your Dictionary & Modifying Them
First, if you ever need to verify if any keys in your braille dictionary are uppercase, you can loop through the dictionary's keys and use the isupper() method. If you find uppercase keys and want to append content to their corresponding values, here's a quick way to do it:
# Check for uppercase keys and modify their values for key in myDict.copy(): # Use copy() to avoid issues while modifying the dict mid-loop if key.isupper(): # Example: Append a suffix to the braille code myDict[key] += '000000' # Optional: Convert the key to lowercase while keeping its value myDict[key.lower()] = myDict.pop(key)
That said, looking at your current myDict, all keys are lowercase letters—so this might not be necessary right now. But it's a handy snippet if you ever expand your dictionary later!
2. Handling Uppercase Input Letters (Adding the '000001' Prefix)
Your main requirement is to prepend 000001 to the braille code whenever the user inputs an uppercase letter. Let's modify your braille function to handle this seamlessly:
Modified Full Code
myDict = { 'a': '100000', 'b': '110000', 'c': '100100', 'd': '100110', 'e': '100010', 'f': '110100', 'g': '110110', 'h': '110010', 'i': '010100', 'j': '010110', 'k': '101000', 'l': '111000', 'm': '101100', 'n': '101110', 'o': '101010', 'p': '111100', 'q': '111110', 'r': '111010', 's': '011100', 't': '011110', 'u': '101001', 'v': '111001', 'w': '010111', 'x': '101101', 'y': '101111', 'z': '101011' } def braille(string, brailleDict): braille_parts = [] for char in string: if char.isupper(): # Add the uppercase prefix first braille_parts.append('000001') # Convert to lowercase to match dictionary keys char = char.lower() # Append the corresponding braille code braille_parts.append(brailleDict[char]) # Join all parts into one continuous string return ''.join(braille_parts) # Test with your example input print(braille('Bob', myDict)) # Output: 000001110000101010110000
How It Works
- We use a list (
braille_parts) to build the result efficiently (this is faster than string concatenation in loops). - For each character in the input string:
- If it's uppercase, we first add the
000001prefix to the list, then convert the character to lowercase to match your dictionary's keys. - We then look up the lowercase character in the dictionary and add its braille code to the list.
- If it's uppercase, we first add the
- Finally, we join all elements of the list into a single string to return.
Testing this with 'Bob' gives exactly the output you wanted: 000001110000101010110000 (prefix for 'B' + 'b'’s code + 'o’'s code + 'b’'s code).
内容的提问来源于stack exchange,提问作者Trey Wessel

