我正在编写一个函数,它将迭代一个文本项列表 - 解析每个项目,并将解析后的项目追加到列表中。 代码如下:
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等,并按照函数的步骤进行试验;这很好用。
当我使用函数(和循环)时,为什么会遇到此错误?