IndexError:字符串索引超出if语句的范围

时间:2017-06-12 23:59:35

标签: python python-3.x

我试图让我的程序将一个句子分成一个列表

alpha =["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
def PARSE(inpu):     #Parse and remove symbols
PARSE = list()
d = 0

intv = 0
output = 0
for i in range (len(inpu)):
    intv = intv + 1
    if inpu[intv] in alpha:
        output = output, inpu[intv]
intv = 0
LI1 = 1
LI2 = 1
while len[output] != LI1 - 1:
    PARSE.append("")
    while not len[output] - 1 < LI1 or not output[LI1] == '':
        PARSE[LI2 - 1] = PARSE[LI2] + output[LI1]
        LI1 = LI1 + 1
        last = last + 1
        LI1 = LI1 + 1
        LI2 = LI2 + 1
PARSE[last] = PARSE[last] + output[LI1 - 1]
done = 1

但我得到了这个错误消息

IndexError: string index out of range

on

if inpu[intv] in alpha:

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

您还可以使用内置方法isalpha()

for i in range(len(inpu)):
    if inpu[i].isalpha():

答案 1 :(得分:0)

你的alpha的简写:

import string

alpha = list(string.ascii_lowercase)

答案 2 :(得分:0)

您创建了第二个索引intv,其值为i+1且超出范围。 变化:

for i in range (len(inpu)):
    intv = intv + 1
    if inpu[intv] in alpha:

由:

for i in range (len(inpu)):
    if inpu[i] in alpha:

答案 3 :(得分:0)

如果您要过滤掉所有标点符号和符号,请尝试以下操作:

import string

def Parse(inpu)

   return ''.join(i for i in inpu if i.lower() in string.ascii_lowercase)