Python:如何分隔函数读取文件并显示用户输入

时间:2019-03-06 05:36:04

标签: python python-3.x list file tuples

我很难分开这些功能。我试图拥有一个读取函数,在该函数中读取我拥有的文本文件(在文本文件中以“,”分隔)。但是,我目前在display_university下拥有它。显示功能应根据以下代码显示类似“ if”类别的格式。 ["UniversityName"]["ContactName"]都是文本文件的标题。(就像从数据库中读取并在该标题下显示内容一样。)

当前文本文件如下:

"UniversityName","ContactName"
"UCLA","John Kelly"
"UofFlorida","Mary Elizabeth"
"U of Memphis","Taylor Johnson"
"Harvard","Robert Fax"

因此,取决于用户输入的内容,它将在该标题下显示内容。现在我拥有大学和联系方式。在主文件上,我可以让用户选择要显示的内容。

我现在的程序应该按大学或联系方式进行排序。因此,如果我选择1.(大学),则输出应按顺序列出所有大学名称:

University: Harvard
Name: Robert Fax

University: UCLA
Name: John Kelly

Name: UofFlorida
Name: Mary Elizabeth
....

此刻,我已注释了读取功能以及如何显示。由于我的打印语句,我只是不知道如何分隔功能。我一直在收到怪异的循环错误。我觉得我的位置有误。

代码:

import csv

def display_university(filename, category):
    with open(filename, mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        line_count = 0
        for row in csv_reader:
           if line_count == 0:
                print(f'{", ".join(row)}')
                line_count += 1
        if category == "University":
            print(f'University: {row["UniversityName"]}'
                  f'\nName: {row["ContactName"]}')
        if category == "Contact":
            print(f'Contact: {row["ContactName"]}'
                  f'\nUniversity: {row["UniversityName"]}')
        line_count += 1
    print(f'\nProcessed {line_count} lines.')


def main():
    filename = "List.txt"

    # list_files = read_file(filename)
    try:
        print("1. University")
        print("2. Contact Name")
        choice = input()
        choice = int(choice)

        if choice == '1':
            # display_university(list_files, "University")
        elif choice == '2':
            # display_university(list_files, "Contact")

        else:
            raise ValueError("Invalid option selected")

    except ValueError:
        print("Unexpected error.")

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:2)

我正在猜测,您正在寻找类似的内容。将CSV读取到dict中,其中每个键是大学名称,值是一个字符串形式的联系人列表。然后有一个单独的功能,从该字典中选择要打印的内容。

import csv
import logging

def read_university_contacts(filename):
    """
    Read CSV file into a dict and return it.
    """
    with open(filename, mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        university_contacts = dict()
        for line_count, row in enumerate(csv_reader, 1):
           if line_count == 1:
                # Not sure why you have this, skip header?
                #continue
                pass
           university = row["UniversityName"]
           contact = row["ContactName"]
           if university not in university_contacts:
               university_contacts[university] = [contact]
           else:
               university_contacts[university].append(contact)
    # Use logging for diagnostics
    logging.info(f'Processed {line_count} lines')
    # Return the structure we read
    return university_contacts    

def main():
    logging.basicConfig(level=logging.INFO, format='%(module)s:%(asctime)s:%(message)s')
    contacts = read_university_contacts("List.txt")

    while True:
        try:
            print("1. University")
            print("2. Contact Name")
            choice = input()
            choice = int(choice)
            break
        except ValueError:
            logging.warning("Unexpected error.")

    # Don't compare to string; you converted to int() above
    if choice == 1:
        print(list(contacts.keys()))
    elif choice == 2:
        print(list(contacts.values()))
    else:
        raise ValueError("Invalid option selected")


if __name__ == "__main__":
    main()