到目前为止,这是我的代码:
readFile = open("ascii_vals.txt", 'r')
writeFile = open("ascii_art.txt", 'w')
EOF = False
while not EOF:
line = readFile.readline()
if line == "":
EOF = True
else:
for char in list(line):
art = chr(int(line))
writeFile.write(art)
该程序的目的是将数字文件转换为ASCII艺术。我的第一个问题是出现此错误:
Traceback (most recent call last):
File "C:/Users/Ethan/Desktop/EthanWork/Python/Python Projects/Uni
Work/asciiNumToChar/Main.py", line 14, in <module>
art = chr(int(line))
ValueError: invalid literal for int() with base 10: '51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,51,53,44,5
第二,使用for char in list(line)
只能对一位数字进行操作。例如,如果使用数字51,则将其分为5和1,我不希望这样,因为如果在chr()
函数中使用它们会产生不同的结果
任何帮助将不胜感激。
答案 0 :(得分:1)
两个错误:
for char in list(line):
line
中包含逗号。您必须按逗号将其分开。调用list
不会这样做。相反:
for char in line.strip().split(",")
然后在下一行:
art = chr(int(line))
您应该将char
转换为int
,而不是整行。
art = chr(int(char))
但是,如果您的数据不如您想象的那么正确,这可能仍然会失败。要对此进行陷阱:
try:
art = chr(int(char))
except ValueError:
art = " "
print ("Invalid data in this line:", line)