【发布时间】:2016-01-07 14:12:26
【问题描述】:
我正在尝试创建一个 Python 程序来读取两个文本文件,一个包含一篇文章,另一个包含“停用词”列表(每行一个词)。我想确定我正在使用的包含文章的特定文本文件中有多少这些“停用词”(每个“停用词”的频率的累积总数)。
我尝试创建嵌套的for 循环以执行此操作,其中我循环遍历包含文章的文件的每一行(外部 for 循环),并且在每一行内都有一个 for 循环(内部 for 循环)循环遍历“停用词”列表,并查看“停用词”是否在当前行中,如果是,多久出现一次。最后,我将单词在当前行中的频率添加到累加器中,该累加器将跟踪在包含文章的文件中找到的停用词的总累积量。
目前,当我运行它时,它说文件中有0个停用词,这是不正确的。
import string
def main():
analyzed_file = open('LearnToCode_LearnToThink.txt', 'r')
stop_word_file = open('stopwords.txt', 'r')
stop_word_accumulator = 0
for analyzed_line in analyzed_file.readlines():
formatted_line = remove_punctuation(analyzed_line)
for stop_word_line in stop_word_file.readlines():
stop_formatted_line = create_stopword_list(stop_word_line)
if stop_formatted_line in formatted_line:
stop_word_frequency = formatted_line.count(stop_formatted_line)
stop_word_accumulator += stop_word_frequency
print("there are ",stop_word_accumulator, " words")
stop_word_file.close()
analyzed_file.close()
def create_stopword_list(stop_word_text):
clean_words = [] # create an empty list
stop_word_text = stop_word_text.rstrip() # remove trailing whitespace characters
new_words = stop_word_text.split() # create a list of words from the text
for word in new_words: # normalize and add to list
clean_words.append(word.strip(string.punctuation).lower())
return clean_words
def remove_punctuation(text):
clean_words = [] # create an empty list
text = text.rstrip() # remove trailing whitespace characters
words = text.split() # create a list of words from the text
for word in words: # normalize and add to list
clean_words.append(word.strip(string.punctuation).lower())
return clean_words
main()
【问题讨论】:
标签: python for-loop readfile readlines