【发布时间】:2020-11-05 03:27:00
【问题描述】:
你好,我是 python 的新手,我正在编写一个模块,它应该将字符串作为输入,输出应该是每个单词、数字或符号的列表,没有空格。即('10个甜苹果')-> ['十','甜','苹果']。为此,我有一个标记当前索引号的起始值和一个结束值,只要字符串中的下一个内容是字母或数字,它就会递增。到目前为止,我已经成功地将单词、数字、符号等添加到要在 for 循环结束时返回的列表中。
当我处于最后一个索引号时,就会出现问题。我有这个代码:
def tokenize (lines):
tokenizedList = []
for line in lines:
endValue = 0
startValue = 0
while startValue < len(line):
if line[endValue].isalpha():
while line[endValue].isalpha():
endValue = endValue + 1
word = line[startValue : endValue]
tokenizedList.append(word)
startValue = endValue
elif line[endValue].isdigit():
while line[endValue].isdigit():
endValue = endValue + 1
word = line[startValue : endValue]
tokenizedList.append(word)
startValue = endValue
elif line[endValue].isspace():
while line[endValue].isspace():
startValue += 1
endValue = startValue
else:
endValue += 1
word = line[startValue : endValue]
tokenizedList.append(word)
startValue = endValue
return tokenizedList
由于 if 语句中的 while 循环递增 endValue,它最终会超出索引范围。我不知道如何阻止此错误的发生以及应该如何更改 while 循环,以便它知道何时停止检查最后一个字母。有什么想法吗?
【问题讨论】:
标签: python list while-loop indexoutofrangeexception