【问题标题】:Python Homework help: issues with counting integers, splitting, and returning most/least common words in text filePython 作业帮助:计算整数、拆分和返回文本文件中最常见/最不常见的单词的问题
【发布时间】:2014-11-29 06:50:57
【问题描述】:

我的家庭作业有很多问题,不幸的是,我对这个概念的理解不如其他人强。但是,我已经编写了大部分代码并且想法很清楚,但很明显我的语法不正确。根据我的任务,我必须这样做:


学生将编写一个程序:

  1. 接受用户输入要处理的文件的名称。如果命名文件不存在,则适当 将发生错误处理,并且将再次请求文件名。这将重复直到 输入有效的文件名或输入字符串“ALL DONE”作为文件名。这 程序将假定命名文件是普通文本文件而不是腌制文件。使用 readline() 函数,而不是 readlines(),来读取文件。

  2. 文件将一次处理一行:

    一个。某些字符将从输入中删除。使用字符串模块, 以下语句将定义要删除的字符。 (string.punctuation + string.whitespace).replace(' ', '')

    b.从输入中删除特定字符后,输入的其余部分 行将在“单词”边界上拆分,其中单词用空格分隔 字符('')。

    c。处理后输入的每个“单词”都将作为键存储在字典中,其中 value 是单词在输入中出现的次数。但是,如果“词” 是一个整数,这个词不会被存储在字典中,而是会被求和 以便显示处理后的文件中所有整数的总和。

  3. 文件处理完毕,会显示如下信息:

    一个。文件中所有整数的总和

    b.文件中最常用的 5 个单词

    c。文件中最不常用的 5 个单词。

    请注意,文件中“最不常见”的单词很可能超过 5 个。在 在这种情况下,您应该打印任何 5 个最不常见的单词。例如,如果有 7 个单词 频率为“1”,然后列出其中的任何 5 个就足够了,但只列出 5 个。


所以,我尽我所能编写了我的代码。我的代码是:

#creates text file
def create_text():
   with open("hw5speech.txt", "wt") as out_file:
    out_file.write(
        """
    Lincoln's Gettysburg Address
    Given November 19, 1863
    Near Gettysburg, Pennsylvania, USA


    Four score and seven years ago, our fathers brought forth upon this continent a new nation:     conceived in liberty, and dedicated to the proposition that all men are created equal.

    Now we are engaged in a great civil war ... testing whether that
    nation, or any nation so conceived and so dedicated ... can long
    endure. We are met on a great battlefield of that war.

    We have come to dedicate a portion of that field as a final resting place for those who here     gave their lives that that nation might live. It is altogether fitting and proper that we should do this.

    But, in a larger sense, we cannot dedicate ... we cannot consecrate ... we cannot hallow this     ground. The brave men, living and dead, who struggled here have consecrated it, far above our poor     power to add or detract. The world will little note, nor long remember, what we say here, but it can     never forget what they did here.

    It is for us the living, rather, to be dedicated here to the unfinished work which they who   fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us ... that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion ... that we here highly resolve that these dead shall not have died in vain ... that this nation, under God, shall have a new birth of freedom ... and that government of the people ... by the people ... for the people ... shall not perish from the  earth.
      """
     )
    out_file.close()

#user input to read a text file
def user_input():
    done = False
    while not done:
        file_prompt = input("What file would you like to open? (name is hw5speech.txt) \
        \n(Or, enter ALL DONE to exit) ")
        if file_prompt == "ALL DONE":
            done = True
        else:
            try:
                text_file = open(file_prompt, "rt")
                return text_file
                done = True
            #required exception handling
            except IOError:
                print("\nThat is not a valid file name. ")
                print()

#read and modify file
def read_file():
    import string
    text_file = user_input()
    for line in text_file.readline():
        myList = line.split(string.punctuation + string.whitespace)#.replace('', " ")
        #myList.split('')                                            

    #store words and integer count
    int_count = 0

    #finds if word is an integer and then adds to count of integers
    def top_integers():
        int_count = 0
        for word in myList:
           test = word.isdigit()
           if test is True:
               int_count += 1

            print("The total of all integers is: ", int_count)

    #finds the 5 most common words
    from collections import Counter
    def t5():
        t5count = Counter(myList.split())
        top5 = t5count.most_common(5)

        print("The 5 most common words are: ")
        for i in top5:
            print(i[0]) #should only print the word and not the count

    #finds the 5 least common words
    def l5():
        l5count = Counter(myList.split())
        least5 = l5count.least_common(5)

        print("The 5 least common words are: ")
        for i in least5:
            print(i[0])

    #calls the above functions
    top_integers()
    t5()
    l5()

#main function of program
def final_product():
    create_text()
    read_file()

final_product()
input("Press Enter to exit.")

所以,当我运行代码时,我输入了文件名 (hw5speech.txt)。这工作正常。然后,它返回 所有整数之和为:0

然后在第 73 行出现 AttributeError 说“list”对象没有属性“split”。myList 是否存在范围问题?

在编程过程中的某一时刻,一切实际上都正常工作,没有任何错误。但是,将返回的是:

The total of all integers is: 0
The 5 most common words are:
The 5 least common words are:

Press Enter to exit.

所以,假设我修复了错误,我确信我仍然会收到空白错误。我到底做错了什么?我在 Stack Overflow 上查看了很多主题并使用了不同的方法,但我要么得到错误,要么不会返回值。我可以查看什么来修复我的代码?

非常感谢大家!

【问题讨论】:

    标签: python string file integer


    【解决方案1】:

    既然是作业而不是回答,我会给你一些提示,当你遇到程序问题时,你需要:

    1. 使用调试器单步执行程序,确保每个阶段都符合您的预期(类型和值)。或者
    2. 在操作之后添加打印语句,以确保您得到您所期望的,(例如,在阅读文本文件后打印出 myList 以确保它是一个列表并且具有所有您所期望的行。

    也可以使用任一方法检查 myList 的类型,对其调用 split 之前。

    【讨论】:

    • 谢谢,感谢您引导我找到答案,而不是只给我答案(:但是,我如何检查它是什么类型?
    • print(type(something)) 将在大多数调试器中完成这项工作或将鼠标悬停在它上面。
    【解决方案2】:
    for line in text_file.readline():
            myList = ...
    

    您正在阅读一行。 for 循环遍历行中的字符,并且每次通过循环时都会覆盖 myList。拆分单个字符会返回一个包含单个字符的列表。

    这就是 myList 的末尾,一个字符的列表,文本第一行的最后一个字符。

    然后:

        for word in myList:
           test = word.isdigit()
    

    这会运行,但 mylist 中唯一的“单词”是“s”,所以它不计算数字,并且这样说。

    然后:

    t5count = Counter(myList.split())
    

    而且您不能拆分列表。 (如果列表正确,您可以将其直接传递给 Counter)。

    您需要使用for line in text_file: 遍历文件中的每一行,并将myList 作为一个空列表开始,然后使用myList += line.split(..)myList.extend(line.split(...)) 将其构建为myList。

    【讨论】:

    • 哦,有道理!那么我应该做一个循环遍历每一行,对吗?我应该将它更改为 text_file 中的 for line 然后让它 readline() 吗?我怎样才能附加这些值?
    • 我刚刚添加到我的答案的末尾,并纠正了我在那里的一个错误。;是的,遍历每一行,你可以使用 readline() 或 readlines(),但由于遍历文件中的每一行是如此常见,如果你循环打开你打开的“文件”,Python 就会这样做,所以你不要也不需要使用。
    • 不幸的是,作业要求使用 readline() 函数:/ 理论上最好的方法是什么?
    • 哦,好的。那么for 循环不是最合适的。如果你调用 readline() 并取回一行,你必须一遍又一遍地调用它 while 你还没有到文件的末尾。
    • 啊,是的,一个while循环!我不知道为什么我之前没有想到这个哈哈。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2019-05-18
    相关资源
    最近更新 更多