python - 我应该如何处理这个IndexError

标签 python list error-handling character indexoutofboundsexception

我正在尝试对此Bigram进行编码,但是已经给出了以下代码:

counts[given][char] += 1 
 IndexError: list index out of range

我不知道该如何处理。谁能帮我?
def pairwise(s):
    a,b = itertools.tee(s)
    next(b)
    return zip(a,b)
    counts = [[0 for _ in range(52)] for _ in range(52)]

with open('path/to/open') as file:
    for a,b in pairwise(char for line in file for word in line.split() for char in word):  
        given = ord(a) - ord('a')                                                            
        char = ord(b) - ord('a')                                                             

        counts[given][char] += 1

我收到此错误:
Traceback: counts[given][char] += 1 IndexError: list index out of range

最佳答案

您的counts变量是pairwise()函数中的局部变量。

这样,尝试在counts循环中以全局方式访问for将会引发NameError。但是,您改为使用一揽子except消除了该异常。不要那样做例如,参见Why is "except: pass" a bad programming practice?。如果您想忽略索引错误,请明确捕获该异常:

except IndexError:
    print 'failed'

并让其他异常到达您,以便您更正错误。

取消缩进counts行,这并不意味着它是pairwise()函数的一部分:
def pairwise(s):
    a,b = itertools.tee(s)
    next(b)
    return zip(a,b)

counts = [[0 for _ in range(52)] for _ in range(52)]

with open('path/to/open') as file:
    for a,b in pairwise(char for line in file for word in line.split() for char in word):  
        given = ord(a) - ord('a')                                                            
        char = ord(b) - ord('a')                                                             
        try:
            counts[given][char] += 1
        except IndexError:
            # unknown character, ignore this one

请注意,对于小写ASCII字母(a-z)以外的任何内容,您产生的索引要么太大要么为负数。 ord('a')是97,但是大写字母的范围是65到90。这意味着您最终会得到-32到-5的整数。那可能不是您想要的。

关于python - 我应该如何处理这个IndexError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27964992/

相关文章:

python - 递归设置文件权限的Python方式是什么?

python - 有没有办法在内部打印 Tornado 网络服务器上配置的路由处理程序?

python - Python 中的函数 "/"参数

python - 如何将列表中的每个项目包装到其正确的列表中

python - 异步运行或 run_until_complete

python - 将字符串追加到列表中的字符串

list - 如何在 Haskell 中折叠状态?

c++ - 不允许的系统调用 : SYS_socketcall - Error when trying to verify ISBN

powershell - 检查网址以获取特定文本,如果匹配则下载,如果名称无法解析则继续下一个

asp.net-mvc - Xero API常规错误处理