尝试在 Python 中创建 Table 盲文

Trying To Create Table To Braille In Python

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

File "brail.py", line 16 stringToWrite=u"\u"+brail([1,1,1,0,0,0,1,1]) ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape

我当前的密码是

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") 但是当我执行一个应该 Return 完全相同的功能时它出错了。

Image Of Code Just In Case

\uPython literal strings 的 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() and 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]))

Python3 中的所有字符串都是 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