如何修复报告功能?

时间:2015-12-08 18:25:40

标签: python pycharm

我的加载库运行良好,我的报告作者计数在Python中有效,但当我将其上传到自动评估时,它说

  

=错误:文件report.txt包含0行,但应包含1行。

def load_library(f):

    with open(f,'rt') as x:
        return dict(map(str.strip, line.split("|")) for line in x)  

def count_authors(file_name):
         invert = {}
         for k, v in load_library(file_name).items():
            invert[v] = invert.get(v, 0) + 1
         return invert


def write_authors_counts(counts, file_name):
        with open(file_name, 'w') as fobj:
            for name, count in counts.items():
                fobj.write('{}: {}\n'.format(name, count))


def report_author_counts(lib_fpath, rep_filepath):
        counts = count_authors(lib_fpath)
        write_authors_counts(counts, rep_filepath)

报告作者计数

  In module library.py, create function report_author_counts(lib_fpath, rep_filepath) which shall compute the number of books of each author and the total number of books, and shall store this information in another text file.

    Inputs:
    Path to a library text file (containing records for individual books).
    Path to report text file that shall be created by this function.
    Outputs: None
    Assuming the file books.txt has the same contents as above, running the function like this:

    >>> report_author_counts('books.txt', 'report.txt')
    shall create a new text file report.txt with the following contents:

    Clarke, Arthur C.: 2
    Herbert, Frank: 2
    Capek, Karel: 1
    Asimov, Isaac: 3
    TOTAL BOOKS: 8
    The order of the lines is irrelevant. Do not forget the TOTAL BOOKS line! If the input file is empty, the output file shall contain just the line TOTAL BOOKS: 0.

    Suggestion: There are basically 2 ways how to implement this function. You can either

    use the 2 above functions to load the library, transform it using index_by_author() and then easilly iterate over the dictionary, or
    you can work directly with the source text file, extract the author names, and count their occurences.
    Both options are possible, provided the function will accept the specified arguments and will produce the right file contents. The choice is up to you.

1 个答案:

答案 0 :(得分:1)

我的猜测是,当你获得一个空的库文本时,你所遇到的基本情况就失败了。输出应该有一行" TOTAL BOOKS:0"但是你的代码中没有这个。

使用以下代码更新您的代码:

def write_authors_counts(counts, file_name):
    tot_books = 0 # new line
    with open(file_name, 'w') as fobj:
        for name, count in counts.items():
            fobj.write('{}: {}\n'.format(name, count))
            tot_books += int(count)  # new line
        fobj.write('TOTAL BOOKS: ' + str(tot_books)) # new line