Python:如何分离函数读取文件和显示用户输入
我很难把这些功能分开。我正在尝试一个read函数,它读取我拥有的文本文件(文本文件中用“,”分隔)。但是,我目前将其放在Python:如何分离函数读取文件和显示用户输入,python,python-3.x,list,file,tuples,Python,Python 3.x,List,File,Tuples,我很难把这些功能分开。我正在尝试一个read函数,它读取我拥有的文本文件(文本文件中用“,”分隔)。但是,我目前将其放在display\u university下。显示功能应根据下面的“我的代码”显示类似“如果”类别的格式。[“UniversityName”]和[“ContactName”]都是文本文件的标题(就像从数据库中读取该标题下的内容一样) 文本文件当前如下所示: "UniversityName","ContactName" "UCLA","John Kelly" "UofFlorida
display\u university
下。显示功能应根据下面的“我的代码”显示类似“如果”类别的格式。[“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函数以及我想显示的内容。我只是不知道如何分离函数,因为我的print语句。我一直有奇怪的循环错误。我觉得我的位置不对
代码:
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()
我猜你在找这样的东西。将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()
我猜你在找这样的东西。将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()
@Mogambo我刚刚在我的解释中添加了它。你的for循环是否正确缩进,因为你粘贴在这里的那一个不是。我推测性地缩进了你的
main
函数定义,因为它是一个语法错误。请复习一下,你比我快。我正要把它修好。谢谢将所有信息放在CSV文件的一行上是一种奇怪且不方便的设计。你有什么办法可以改为修复古怪的输入文件格式吗?@Mogambo我刚刚在我的解释中添加了它。你的for循环是否正确缩进,因为你粘贴在这里的那一个不是。我推测性地缩进了你的main
函数定义,因为它是一个语法错误。请复习一下,你比我快。我正要把它修好。谢谢将所有信息放在CSV文件的一行上是一种奇怪且不方便的设计。你有没有办法修复古怪的输入文件格式,或者也可以?是的!有点,但我觉得你的缩进有问题。我想用我的电脑来运行它,嗯?可能重新加载页面时,我必须在一个位置修复缩进,但我在发布后立即修复了缩进,因此无法作为单独的编辑显示。评论不断将其弄乱,您介意发送一个repl链接或类似的内容吗?抱歉,缩进现在也修复了(不知何故,一个空间太多了)。你是否知道如何按照每所大学的第一个字母和名字对这一行进行排序?是的!有点,但我觉得你的缩进有问题。我想用我的电脑来运行它,嗯?可能重新加载页面时,我必须在一个位置修复缩进,但我在发布后立即修复了缩进,因此无法作为单独的编辑显示。评论不断将其弄乱,您介意发送一个repl链接或类似的内容吗?抱歉,缩进现在也修复了(不知何故,一个空间太多了)。你是否知道如何按照每所大学的第一个字母和名字对这一行进行排序?