我正在编写一个将遍历文本项列表的函数-解析每个项,并将解析后的项附加回列表中。代码如下:
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等,并按照函数的步骤进行操作;这很好。
为什么在使用函数(和循环)时会遇到此错误?
更改while i <= len(list)
为while i < len(list)
列表索引从0
so开始,i <= len(list)
将使索引等于,len(list)
因此将导致索引错误。
1。列表支持循环访问,而不是使用文件循环更好,而不是使用文件循环list
。喜欢
for elem in list_:
# Do your operation here
2。不要list
用作变量名。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句