【问题标题】:ord() expected a character, but string of length 0 found in python codeord() 期望一个字符,但在 python 代码中找到长度为 0 的字符串
【发布时间】:2017-09-12 19:56:44
【问题描述】:

以下是我正在执行的代码

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

执行我得到的代码后,

文件“learn.py”,第 57 行,在

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

TypeError: ord() 需要一个字符,但找到长度为 0 的字符串

我该如何解决?

【问题讨论】:

  • 通过在category 中添加一些内容,这似乎是一个空列表。
  • 另外,请阅读guidelines on how to write good questions,代码应该全部放在问题中,应避免链接到github(因为它们可能随时中断)
  • 我是这个世界的新手,所以请原谅我的错误。急需解决查询。下次会注意的:)
  • 阅读该链接对于初学者来说是一个很好的起点;)如果人们真正清楚地了解您的代码、哪里出了问题以及哪里/如何,您的问题就会得到更快的解决
  • 与其说下次会注意,不如编辑问题以包含相关代码。

标签: python


【解决方案1】:

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

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

name 来自:

for path, subdirs, files in os.walk(root):
    for name in files:

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

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

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

【讨论】:

  • 你做对了。您能帮我在哪里更改代码以使其正常工作吗?我的示例文件名是“a_sample_0_1”,它是串联的。
【解决方案2】:

项目数据目录包含许多文件名以_ 开头的文件,例如_sample_t10_34.txt

所以在你的代码中

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

现在下一行是:

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

这里 ord() 接受长度为 1 的 str 类型的参数,您会收到此错误,因为类别有时会是一个空字符串 '',当名称为 _sample_t10_34.txt 的文件被读取时。

您可以做的是跳过以_ 开头的文件,通过使用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..

【讨论】:

  • 我尝试了您的解决方案,但出现新错误,IndentationError: unindent does not match any external indentation level
  • 在哪一行?
  • 如果我输入,如果不是 name.startswith('_'): 在 "filename = os.path.join(path, name)" 行之前,那么我得到,文件 "learn.py ", line 47 filename = os.path.join(path, name) ^ IndentationError: expected an indented block
  • 你必须从该行缩进代码直到classes[number] = category 4 个空格(推荐)。
  • 简单的解决方案是删除数据文件中所有以_开头的文件&问题解决了:)剩下的所有代码将根据上面提供的github链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-23
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
相关资源
最近更新 更多