python receiving error using ord function "TypeError: ord() expected a character, but string of length 2 found"

python receiving error using ord function "TypeError: ord() expected a character, but string of length 2 found"

我修改了找到的一些 Python 代码,它计算观察到的序列的转换矩阵(此处命名的转换)。

出于某种原因,它工作正常,但是当我输入大于或等于“10”的数字时,出现此错误:

"ord() 需要一个字符,但找到了长度为 2 的字符串"

states_no = 10
transitions = [['10', '1', '1', '2', '3', '1']]
trans_matr = []

for k in range(len(transitions)):


    def rank(c):
        return ord(c) - ord('1')

    T = [rank(c) for c in transitions[k]]
    #print(transitions[k])
    #create matrix of zeros

    M = [[0]*states_no for _ in range(states_no)]

    for (i,j) in zip(T,T[1:]):
        M[i][j] += 1

    #now convert to probabilities:
    for row in M:
        n = sum(row)
        if n > 0:
            row[:] = [f/sum(row) for f in row]

    #print M:
    trans_matr.append(M)
    #for row in M:
        #print(row)
#print(trans_matr)

trans_matr_array=numpy.array(trans_matr)
print(trans_matr_array)

估计跟字符识别有关。有没有什么办法可以把数字加到 14 而不会出现这个错误?

据我所知,代码仅使用 ord() 来计算输入与 1 之间的差异。您的输入是否包含 non-numeric 个字符? 如果不是,只需更改函数“rank”:

def rank(c)
    return int(c) - 1

我假设您只需要整数,您可以将其更改为浮点数以接受任何数字。

如果您还需要接受 non-numeric 个字符:

def rank(c):
    if c.isnumeric():
        return int(c) - 1
    elif len(c) == 1:
        return ord(c) - ord('1')
    else:
        raise TypeError('non numeric inputs should have length 1')