字符串索引超出范围索引

2024-03-29 11:51:19 发布

您现在位置: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),但现在它工作了,因为我只想检查每个单词的第一个字母,它不工作。你知道吗

有什么线索吗?你知道吗


Tags: toinimportreforlenifbin
1条回答
网友
1楼 · 发布于 2024-03-29 11:51:19

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

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

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

相关问题 更多 >