python - 字符串索引超出范围 - 索引错误

标签 python

#!/usr/bin/env python

import sys
import re

# regular expressions

pattern = re.compile("[a-zA-Z]*",
                 re.MULTILINE | re.DOTALL | re.IGNORECASE)

# Read pairs as lines of input from STDIN
for line in sys.stdin:

    # loop through every word that matches the pattern
    for word in pattern.findall(line):
        while i < 1:
            if len(converted_word) != WINDOW:
                # print "word =", word
                if a_to_f_pattern.match(word[i]):
                   .....

            else:
               .....
        i = 0

这行在这里

if a_to_f_pattern.match(word[i]):

给我标题错误,但我不明白为什么

以前,我有while i < len(word)它有效,但现在因为我只想检查每个单词的第一个字母,所以它不起作用。

有什么线索吗?

最佳答案

正则表达式[a-zA-Z]*将匹配空字符串,因为*表示“零个或多个”。请使用 [a-zA-Z]+ 来确保您的单词长度至少为一个字母。

此外,由于您使用的是 re.IGNORECASE,因此无需在模式中同时放入大写和小写字母。如果模式不包含 ^$,则不需要 re.MULTILINE 选项,并且不需要 re .DOTALL 如果模式中没有 .。所以它应该是:

pattern = re.compile("[a-z]+", re.IGNORECASE)

关于python - 字符串索引超出范围 - 索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36875348/

相关文章:

python - 设置Python包的顶级

python - 使正则表达式适应 python re 模块

python - 在 python 中将文件路径作为命令行参数传递

python - Try except 错误异常 - KeyError

python - 如何通过多值列过滤JSON数据

Python 骰子结果计数

python - 如何在 python 解释器 shell 中重复最后一个命令?

python - 在 python 中使用带宽方法进行投资组合再平衡

python - 使用 imshow 和 imwrite 的 Opencv 不同输出

python - 如何在 Matplotlib 中旋转表头?