如何使用"in"功能从列表中删除某些单词


def calculate_frequencies(file_contents):
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 punctuation in punctuations:
file_contents = file_contents.replace(punctuation,"")



file_contents = file_contents.lower()
file_contents = file_contents.split()

for word in file_contents:
if word in uninteresting_words:
file_contents.remove(word)

word_count = {}
for word in file_contents:
if word not in word_count.keys():
word_count[word]= 1
else :
word_count[word]+= 1
return print(file_contents)
calculate_frequencies(file_contents)

这是我的代码,file_contents是一个。txt文件,我需要过滤掉所有标点符号和所有无趣的单词。我去掉了所有的标点符号,但去掉那些无趣的词却很困难。我觉得这应该已经完成了工作,但当我运行代码时,周围仍然有无趣的话,我做错了什么?

您可以在for循环中忽略它们,而不是尝试删除不感兴趣的单词,像这样:

def calculate_frequencies(file_contents):
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 punctuation in punctuations:
file_contents = file_contents.replace(punctuation, "")
file_contents = file_contents.lower()
file_contents = file_contents.split()

word_count = {}
for word in file_contents:
if word not in uninteresting_words:
if word not in word_count.keys():
word_count[word] = 1
else:
word_count[word] += 1
return print(file_contents)

calculate_frequencies(file_contents)

最新更新