【问题标题】:Word Count from File: Is it having problems opening the file, or have I coded it incorrectly?文件中的字数:打开文件有问题,还是我编码不正确?
【发布时间】: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

【问题讨论】:

  • 您添加到单词列表中的唯一单词是文件名。

标签: python file count word


【解决方案1】:

与 Mac 和 Linux 操作系统相比,使用 python 在 windows 中导入文件有些不同

只需将文件路径更改为fname = r"C:\Users\....\Desktop\Sense_and_Sensibility.txt"

fname = "C:\\Users\\....\\Desktop\\Sense_and_Sensibility.txt"

使用双斜线

【讨论】:

  • 你确定吗?开始时,这些文件是打开的,而不是导入的(这在 Python 中意味着它们是通过import 使用的)。除此之外,r(代表 raw)限定符实际上忽略了 C 风格的转义,这意味着 \ 总是被视为 \\ ,并且不需要用 \\ 或它将有一个特殊的解释,例如正如\t 那样。
【解决方案2】:

您的代码存在几个问题。我只讨论最明显的一个,因为不可能重现您的确切观察结果,因为读者无法访问您使用的输入。

我将首先逐字报告您的代码,并用??? 后跟一个数字标记弱点,我将在代码后解决。

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:                 #???(1) have the program run the file  
    for line in file:                     #loop through                                     
       fname.replace ('-.,"!?', " ")         #???(2) replace punc. with space
       words = fname.lower()                 #???(3) make all words lowercase

       word_list = fname.split()             #separate the words, store 

       word_dict = {}                        #???(4) 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)    #???(5) delete common words




    for word in word_list:                            #???(6) loop through
        word_dict[word] = word_dict.get(word, 0) + 1  #???(7) count frequency

    word_freq = []                                    #???(8)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
  1. (次要)file 是 Python 中的保留字,最好不要像您正在做的那样用于自定义目的
  2. (major) .replace() 将用右边的确切字符串替换左边的确切字符串,但您想做的是执行某种multi_replace(),您可以自己实现(例如作为函数)通过​​连续调用.replace(),例如在循环中(或使用functools.reduce())。
  3. (主要)fname 包含文件名(实际上是路径),而不是您要使用的文件的内容。
  4. (主要)您正在循环文件的行,但如果您为每一行创建word_listword_dict,您将在每次迭代时“覆盖”内容。此外,word_dict 被创建为空且从未填充。
  5. (主要)您尝试实现的逻辑不适用于字典,因为字典不能包含多个相同的键。更有效的方法是通过排除stop_wordsword_list 创建filtered_list。然后可以使用字典来实现计数器。我确实理解在您的水平上学习如何实现计数器可能是值得的,但请记住,标准库中的模块 collections.Counter()(因此可以使用 import collections 访问)正是您想要的。
  6. (主要)鉴于此时您的代码中没有任何有用的信息,但是循环遍历原始列表而不是过滤列表将没有关于停用词的信息。
  7. (主要)dictionary[key] 可用于访问(您不会这样做)和写入(您会这样做)与字典中特定键关联的值。
  8. (次要)显然,您根据词频进行排序的方法可行,但更好的方法是使用.sort()sorted() 的参数key

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多