【发布时间】:2019-02-10 06:22:10
【问题描述】:
问题:程序似乎无法打开要读取的文件。
我的问题是,一开始程序似乎被破坏了。它只是显示
[(1, 'C:\Users\....\Desktop\Sense_and_Sensibility.txt')]
一遍又一遍,永无止境。
(注意: .... 是为了发帖而替换,因为我的计算机用户名是我的全名)。
我不确定我的编码是否完全错误,或者是否在打开文件时遇到问题。任何帮助表示赞赏。
程序应该:
1:打开一个文件,用空格替换所有标点符号,将所有单词改为小写,然后将它们存储在字典中。
2:查看将从原始字典中删除的单词列表(停用词)。
3:统计剩余单词并根据频率排序。
fname = r"C:\Users\....\Desktop\Sense_and_Sensibility.txt" # file to read
swfilename = r"C:\Users\....\Desktop\stopwords.txt" # words to delete
with open(fname) as file: # have the program run the file
for line in file: # loop through
fname.replace('-.,"!?', " ") # replace punc. with space
words = fname.lower() # make all words lowercase
word_list = fname.split() # separate the words, store
word_dict = {} # create a dictionary
with open(swfilename) as delete: # open stop word list
for line in delete:
sw_list = swfilename.split() # separate the words, store them
sw_dict = {}
for key in sw_dict:
word_dict.pop(key, None) # delete common words
for word in word_list: # loop through
word_dict[word] = word_dict.get(word, 0) + 1 # count frequency
word_freq = [] # create index
for key, value in word_dict.items(): # count occurrences
word_freq.append((value, key)) # append freq list
word_freq.sort(reverse=True) # sort the words by freq
print(word_freq) # print most to least
【问题讨论】:
-
您添加到单词列表中的唯一单词是文件名。