ord()需要一个字符,但在python cod中找到长度为0的字符串

2024-10-01 13:39:33 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我正在执行的代码

https://github.com/federico-terzi/gesture-keyboard/blob/master/learn.py

在执行我得到的代码之后

“文件”学习.py“,第57行,英寸

number = ord(category) -ord('a')

TypeError: ord() expected a character, but string of length 0 found

我怎样才能修好它?在


Tags: 文件代码pyhttpsgithubmastercomlearn
2条回答

查看链接到的代码,category来自

category = name.split("_")[0]

并且name来自:

^{pr2}$

所以我猜你有一个带前导下划线的文件名。将此字符串拆分到'_'这将为列表的第一个值提供一个空字符串。示例:

s = '_abc_test.txt'
s.split('_')
# returns:
['', 'abc', 'test.txt']

它的第零个元素是一个空字符串,它被传递给ord。在

项目数据目录包含许多文件,其文件名以_开头,类似于_sample_t10_34.txt。在

所以在你的代码里

for path, subdirs, files in os.walk(root):
    for name in files:
        category = name.split("_")[0] # here category = ''

现在下一行是:

^{pr2}$

在这里,^{}接受长度为1的str类型的参数,您会得到这个错误,因为当名称为_sample_t10_34.txt的文件被ign read时,category有时会是一个空字符串''。在

您可以跳过以_开头的文件,方法是使用if statement检查该文件是否以_开头。在

for path, subdirs, files in os.walk(root):
    for name in files:
        if not name.startswith('_'):
            # code here after if statement
            category = name.split("_")[0]
            number = ord(category) - ord("a")
            # rest of code..

相关问题 更多 >