尝试在Python中创建盲文表



我一直在尝试创建一个系统,将1和0的表转换为盲文字符,但它一直给我这个错误

文件"brail.py",第16行stringToWrite = u" u" +抄网([1,1,1,0,0,0,1,1])^SyntaxError:(unicode错误)'unicodeescape'编解码器无法解码位置0-1的字节:truncated uXXXX escape

My Current Code Is

def brail(brailList):
if len(brailList) == 8:
brailList.reverse()
brailHelperList=[0x80,0x40,0x20,0x10,0x8,0x4,0x2,0x1]
brailNum=0x0
for num in range(len(brailList)):
if brailList[num] == 1:
brailNum+=brailHelperList[num]
stringToReturn="28"+str(hex(brailNum))[2:len(str(hex(brailNum)))]
return stringToReturn
else:
return "String Needs To Be 8 In Length"
fileWrite=open('Write.txt','w',encoding="utf-8")
stringToWrite=u"u"+brail([1,1,1,0,0,0,1,1])
fileWrite.write(stringToWrite)
fileWrite.close() 

当我做fileWrite.write(u"u28c7")时它工作,但是当我做一个应该返回完全相同的东西的函数时它错误。

代码图片,以防万一

u是Python字面值字符串的unicode转义序列。转义序列后面应该有一个4十六进制的unicode码点。如果缺少代码点或代码点太短,则表示语法错误。

>>> 'u28c7'
'⣇'
>>> 'u'
File "<stdin>", line 1
'u'
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated uXXXX escape

如果你正在使用Python 3,那么u字符串前缀是不需要的,因为字符串内部存储为unicode。u前缀是为了与Python 2代码兼容而保留的。

这是导致异常的原因,但是,您不需要像这样构造unicode码点。您可以使用ord()chr()函数:

from unicodedata import lookup
braille_start = ord(lookup('BRAILLE PATTERN BLANK'))
return chr(braille_start + brailNum)

你可以重写

stringToWrite=u"u"+brail([1,1,1,0,0,0,1,1])

stringToWrite="\u{0}".format(brail([1, 1, 1, 0, 0, 0, 1, 1]))

所有字符串在Python 3中都是unicode,所以你不需要前面的"u"

def braille(brailleString):
brailleList = []
brailleList[:0]=brailleString
if len(brailleList) > 8:
brailleList=brailleList[0:8]
if len(brailleList) < 8:
while len(brailleList) < 8:
brailleList.append('0')
brailleList1=[
int(brailleList[0]),
int(brailleList[1]),
int(brailleList[2]),
int(brailleList[4]),
int(brailleList[5]),
int(brailleList[6]),
int(brailleList[3]),
int(brailleList[7]),
]
brailleList1.reverse()
brailleHelperList=[128,64,32,16,8,4,2,1]
brailleNum=0
for num in range(len(brailleList1)):
if brailleList1[num] == 1:
brailleNum+=brailleHelperList[num]
brailleStart = 10240
return chr(brailleStart+brailleNum)
fileWrite=open('Write.txt','w',encoding="utf-16")
fileWrite.write(braille('11111111'))
fileWrite.close()
# Think Of The Braille Functions String Like It Has A Seperator In The Middle And The 1s And 0s Are Going Vertically

相关内容

  • 没有找到相关文章

最新更新