Py学习  »  Python

Python:如何分离函数read file和显示用户输入

smokingpenguin • 6 年前 • 1640 次点击  

我很难把这些功能分开。我正在尝试一个read函数,它读取我拥有的文本文件(在文本文件中用“,”分隔)。不过,我现在把它放在 display_university . display函数应该根据下面的代码显示类似于“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
....

我现在已经注释了read函数,以及我想如何显示。我只是不知道如何分离函数,因为我的打印语句。我一直有奇怪的循环错误。我觉得我的位置不对。

代码:

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()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51258
文章 [ 1 ]  |  最新文章 6 年前
tripleee
Reply   •   1 楼
tripleee    7 年前

我是 猜测 你在找这样的东西。将CSV读入 dict 其中,每个键是一个大学名,值是一个联系人列表(作为字符串)。然后有一个单独的函数选择要从该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()