【发布时间】:2021-10-01 06:01:25
【问题描述】:
我正在尝试编写一段代码,帮助我删除所有连词代词、标点符号等。
macbeth = open("macbeth.txt", "r")
contents = macbeth.read()
contents = contents.split()
def remove_uninteresting_stuff(file_contents):
# Here is a list of punctuations and uninteresting words you can use to process your text
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \
"we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \
"their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \
"have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \
"all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"]
for x in punctuations:
file_contents.remove(x)
for x in uninteresting_words:
file_contents.remove(x)
return file_contents
print(remove_uninteresting_stuff(contents))
此代码引发此错误:
Traceback (most recent call last):
File "testingFile.py", line 33, in <module>
print(remove_uninteresting_stuff(contents))
File "testingFile.py", line 25, in remove_uninteresting_stuff
file_contents.remove(x)
ValueError: list.remove(x): x not in list
现在很明显,在麦克白(莎士比亚的)这样的小说中,这些词会存在。
谁能解释这个错误并帮我解决这个问题?
【问题讨论】:
-
哪个词失败了?
print(x)在失败行之前。 -
或者您可能不在乎文本不包含特定的单词,只需将
file_content.remove用try/except块包围。
标签: python list valueerror