python - 如何反转字典中的另一个函数以及如何计算反转值(如果它在报告中不唯一)?

标签 python

我的加载库运行良好,但另一个也失败了.. 如何反转字典中的另一个函数(按作者索引)以及如何计算反转值(如果它在报告中不唯一)(报告作者计数)?

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

        def index_by_author(f):    
            return {value:key for key, value in load_library(f).items()}

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, implement function load_library().

Inputs:
Path to a text file (with contents similar to those above) containing the individual books.
Outputs:
The function shall produce a dictionary where the book titles are used as keys and the authors' names are stored as values.
You can expect that the input text file will always exist, but it may be empty. In that case, the function shall return an empty dictionary.

It can then be used as follows:

>>> from library import load_library
>>> book_author = load_library('books.txt')
>>> print(book_author['RUR'])
Capek, Karel
>>> print(book_author['Dune'])
Herbert, Frank

作者索引

In module library.py, create function index_by_author(), which - in a sense - inverts the dictionary of books produced by load_library().

Inputs:
A dictionary with book titles as keys and book authors as values (the same structure as produced by load_library() function).
Outputs:
A dictionary containing book authors as keys and a list of all books of the respective author as values.
If the input dictionary is empty, the function shall produce an empty dictionary as well.

For example, running the function on the following book dictionary (with reduced contents for the sake of brevity) would produce results shown below in the code:

>>> book_author = {'RUR': 'Capek, Karel', 'Dune': 'Herbert, Frank', 'Children of Dune': 'Herbert, Frank'}
>>> books_by = index_by_author(book_author)
>>> print(books_by)
{'Herbert, Frank': ['Dune', 'Children of Dune'], 'Capek, Karel': ['RUR']}
>>> books_by['Capek, Karel']
['RUR']
>>> books_by['Herbert, Frank']
['Dune', 'Children of Dune']

报告作者计数

    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.

python

最佳答案

index_by_author 函数需要比您建议的字典理解稍微复杂一些。 dict.setdefault() 在这里派上用场,如 Efficient way to either create a list, or append to it if one already exists? 中所述。 。还要注意,您的作业表明参数应该是字典,而不是文件。这是我的建议:

def index_by_author(book_author):
    dict_by_author = {}
    for key, value in book_author.items():
        dict_by_author.setdefault(value, []).append(key)
    return dict_by_author

然后在您的 report_author_counts() 中,您可以使用 index_by_author() 来反转字典。然后循环遍历倒排字典。对于每个项目,计数将是值的长度,该值将是标题列表。列表的长度由 len(list) 确定。

关于python - 如何反转字典中的另一个函数以及如何计算反转值(如果它在报告中不唯一)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34159652/

相关文章:

python - 使用scipy对数正态分布拟合小值数据,然后在matplotlib中显示

javascript - 当您通过 onclick 提交时,获取在服务器上单击了哪个按钮

python - 如何在 Django 查询集中执行 AND 条件?

python - 查找带有 beautifulsoup 的特定链接

python - 使用导入行上传 Fusion Tables 数据失败并出现 Http 错误 500 : Backend Error

python - 如何使用 pandas.read_excel() 直接从 Dropbox 的 API 读取 Excel 文件?

python - 在 Pandas 中编码列标签以进行机器学习

python - Pandas,映射两个数据帧,根据条件进行计数

python - Python 中的 Sigma 表示法

python - 将日期范围转换为 Numpy 数组,作为 Pandas 中 Groupby 的一部分