*问题陈述:我正在尝试编写一个接受字符串和列表的函数.
-我将使用的一串单词.split()
方法转换为列表
-使列表中的所有单词都小写,以使检查统一
-遍历列表检查,查看字符串列表中是否包含数组中的单词.
-如果是,则会删除该单词
-将非填充词列表重新连接到字符串中
回溯:
Traceback (most recent call last):
File "main.py", line 55, in <module>
no_filler = remove_filler_words(no_punction,filler_words);
File "main.py", line 37, in remove_filler_words
word_list[cap_word] = word_list[cap_word].lower()
IndexError: list index out of range
代码:
def remove_filler_words(cleaned_string:string, filler_words:list):
cleaned_sentence = ""
word_list = cleaned_string.split()
for cap_word in range(len(word_list)):
word_list[cap_word] = word_list[cap_word].lower()
for filler_word in filler_words:
if filler_word in word_list:
word_list.remove(filler_word)
line_join = " ".join(word_list)
cleaned_sentence += line_join
return cleaned_sentence
以下是我提出的解决方案:
def remove_filler_words(cleaned_string, filler_words):
word_list = cleaned_string.split()
new_word_list = []
for cap_word in range(len(word_list)):
lower_word = word_list[cap_word].lower()
new_word_list.append(lower_word)
for filler_word in filler_words:
if filler_word in new_word_list:
new_word_list.remove(filler_word)
cleaned_sentence = " ".join(new_word_list)
return cleaned_sentence
我将所有保存到lower_word
的小写单词添加到一个新列表中,以解释索引错误.然后,我没有在开始时声明空列表,而是将cleaned_sentence
变量分配给连接函数,该函数在返回时生成预期结果.
尝试创建
word_list
的副本,例如copy_word_list
并从此变量中删除单词.代码如下:
希望有帮助)