#!/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/