2017-02-23 92 views
1

我正在编写一个函数,它将遍历文本项目列表 - 解析每个项目,并将解析的项目追加到列表中。 的代码如下:列表索引超出范围 - 索引错误Python

clean_list = [] 

def to_words(list): 
    i = 0 
    while i <= len(list): 
     doc = list[i] 
     # 1. Remove HTML 
     doc_text = BeautifulSoup(doc).get_text() 
     # 2. Remove non-letters (not sure if this is advisable for all documents)  
     letters_only = re.sub("[^a-zA-Z]", " ", doc_text) 
     # 3. Convert to lower case, split into individual words 
     words = letters_only.lower().split()            
     # 4. Remove stop words 
     stops = set(stopwords.words("english")) 
     meaningful_words = [w for w in words if not w in stops] 
     # 5. Join the words back into one string separated by space, and return the result. 
     clean_doc = (" ".join(meaningful_words)) 
     i = i+1 
     clean_list.append(clean_doc) 

但是当我通过列表进入该功能,to_words(list),我得到这个错误:IndexError: list index out of range

我尝试没有技术上的定义to_words功能,即避免了循环试验,手动将i改为0,1,2等,然后执行该功能的步骤;这工作正常。

为什么我在使用函数(和循环)时面临这个错误?

+0

你能在这里给出完整的回溯吗? –

+2

长度为5的列表具有索引'0,1,2,3,4'。 - 你的'而我<= len(列表)'给出'我'值'0,1,2,3,4,5'。将它改为'while while asongtoruin

+1

也不要使用变量名'list',因为这会导致与'list'对象类型混淆。 – asongtoruin

回答

1

变化 while i <= len(list)while i < len(list)

目录索引开始从0所以,i <= len(list)将满足指数等于len(list)所以这是将一个索引错误。

1。更好地使用而不是使用文件循环,列表支持迭代list。像

for elem in list_: 
    # Do your operation here 

2。请勿使用list作为变量名称。