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

如何修复Python二进制字符转换器输出全部为UNKNOWN的问题

问题描述

我是编程新手,目前遇到输出不符合预期的问题。我的需求是导入一个包含A-Z、a-z及多个特殊字符对应值的CSV文件,将数据的第1行、第2行传入createDictionary函数读取。我编写characterTranslator函数的目标是将这两行数据存入空字典,以便操作键值对,最终转换器可将给定测试字符串中存在的键对应的字符转换为匹配的二进制值。但目前二进制值转换失败,所有输出均为UNKNOWN,不知道如何修复。

原代码
import csv

def createDictionary():  # opens, reads, and assigns the characters to the key and the binary to the value pairs
    # opens the file needed to work with
    with open(r"C:\Users\phill\Downloads\ASCIICharacterCodes (1).csv", "r") as data:
        reader = csv.reader(data)
        dict_from_csv = {rows[1]: rows[0]for rows in reader}
        return(dict_from_csv)

def characterTranslator():
    translated_dictionary = {}
    for key, value in mydict.items():
        translator = ''.join(bin(ord(c)) for c in value).replace('b', '')
        translated_dictionary[key] = translator
        return translated_dictionary

print("before translation")
mydict = createDictionary()

#print(mydict)

print("\n\nAfter translation")
mapping = characterTranslator()

sentence = "Hello World! Welcome to 'programing' world :)"
file = open("output.txt",'w')
for ch in sentence:
    if(ch in mapping.keys()):
        file.write(ch + " " + str(mapping[ch]) + "\n")
    else:
        file.write(ch + " " + "UNKNOWN" + "\n")
file.close()
输出结果
H UNKNOWN
e UNKNOWN
l UNKNOWN
l UNKNOWN
o UNKNOWN
  UNKNOWN
W UNKNOWN
o UNKNOWN
r UNKNOWN
l UNKNOWN
d UNKNOWN
! UNKNOWN
  UNKNOWN
W UNKNOWN
e UNKNOWN
l UNKNOWN
c UNKNOWN
o UNKNOWN
m UNKNOWN
e UNKNOWN
  UNKNOWN
t UNKNOWN
o UNKNOWN
  UNKNOWN
' UNKNOWN
p UNKNOWN
r UNKNOWN
o UNKNOWN
g UNKNOWN
r UNKNOWN
a UNKNOWN
m UNKNOWN
i UNKNOWN
n UNKNOWN
g UNKNOWN
' UNKNOWN
  UNKNOWN
w UNKNOWN
o UNKNOWN
r UNKNOWN
l UNKNOWN
d UNKNOWN
  UNKNOWN
: UNKNOWN
) UNKNOWN
修复方案
  • 核心问题:characterTranslator函数中return语句缩进错误,放在了for循环内部,导致函数只遍历了字典的第一个键值对就直接返回,最终生成的mapping字典只有1条数据,测试字符串里的绝大多数字符都匹配不到,只需要把return语句调整到和for循环同级的位置即可。
  • 次要问题:二进制格式转换逻辑有问题,bin(ord(c))生成的字符串前缀是0b,仅替换b会保留开头的0,如果需要标准的无前缀二进制编码,应该替换0b而不是仅替换b。
  • 优化点:读写文件建议用with上下文管理器,自动处理文件关闭,避免资源泄漏。
修复后代码
import csv

def createDictionary():
    with open(r"C:\Users\phill\Downloads\ASCIICharacterCodes (1).csv", "r") as data:
        reader = csv.reader(data)
        dict_from_csv = {rows[1]: rows[0] for rows in reader}
        return dict_from_csv

def characterTranslator():
    translated_dictionary = {}
    for key, value in mydict.items():
        translator = ''.join(bin(ord(c)) for c in value).replace('0b', '')
        translated_dictionary[key] = translator
    # return调整到for循环外
    return translated_dictionary

print("before translation")
mydict = createDictionary()

print("\n\nAfter translation")
mapping = characterTranslator()

sentence = "Hello World! Welcome to 'programing' world :)"
# 用with管理文件写入
with open("output.txt",'w') as file:
    for ch in sentence:
        if ch in mapping:
            file.write(f"{ch} {mapping[ch]}\n")
        else:
            file.write(f"{ch} UNKNOWN\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:27:03