【发布时间】:2021-12-07 19:36:40
【问题描述】:
我是编程新手,正在努力获得所需的输出。 我的目标是导入一个 csv 文件,其中填充了不同的值,包括 A-Z、a-z 和几个不同的特殊字符。我将数据的第 1 行和第 2 行放入 createDictionary 函数中进行读取。我使用 characterTranslator 的目标是将第 1 行和第 2 行放入一个空字典中,以便我可以操作键/值对。从那里我希望翻译器将给定测试字符串中存在的任何键值转换为相应的二进制值。但是二进制值没有被正确翻译,我不确定如何修复它。
这是我目前的代码:
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
【问题讨论】:
-
您好,您不应该发布您的代码的屏幕截图,因为其他人必须重新输入代码,这可能会花费他们很多时间。您也可以找到how to post a good, minimal, and reproducible example of your code,以便更快地回答您的问题。
-
您的具体问题是什么?您发布了一些代码的图像,但不清楚您遇到了什么问题?还有meta.stackoverflow.com/questions/285551/…
-
嗨 Grismar,我很抱歉这是我的第一篇文章。问题是当我翻译我的测试字符串时,对应于键/值对的二进制值没有返回。输出中每个字母旁边应该是对应的二进制值。