【问题标题】:Python: How to separate the function read file and display user inputPython:如何分离函数读取文件并显示用户输入
【发布时间】:2019-03-06 05:36:03
【问题描述】:

我很难分离这些功能。我正在尝试有一个读取功能,它可以读取我拥有的文本文件(在文本文件中用“,”分隔)。但是,我目前在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()

【问题讨论】:

  • @Mogambo 我刚刚在我的解释中添加了它
  • 您的 for 循环是否正确缩进,因为您在此处粘贴的循环不是
  • 我推测性地缩进了您的 main 函数定义,因为正如发布的那样,这是一个语法错误。请查看。
  • @tripleee 你打败了我。我正要修复它。谢谢!
  • 将所有信息放在 CSV 文件的一行中是一种奇怪且不方便的设计。有什么办法可以改正古怪的输入文件格式吗?

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


【解决方案1】:

你正在寻找这样的东西。将 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()

【讨论】:

  • 是的!有点,但我认为你的缩进已经关闭。我正在尝试在我的 IDE 上运行它
  • 嗯?也许重新加载页面,我不得不在一个地方修复缩进,但我在发布后立即这样做了,所以它作为单独的编辑不可见。
  • cmets 一直在搞砸,你介意发送一个 repl 链接或类似的东西吗?
  • 对不起,缩进现在也固定在这里(一个空格太多不知何故悄悄进入)。还有repl.it/repls/FirebrickShallowProperties
  • 你知道如何按每所大学和名称的首字母对行进行排序吗?
猜你喜欢
  • 2021-01-01
  • 1970-01-01
  • 2021-11-24
  • 2021-03-23
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多