我有一个名为codes.csv的csv文件,如下所示。
CATEGORY SUB-CATEGORY
Technology Accessories
Technology Phones
Technology Copier
Technology Machines
Furniture Chairs
Furniture Tables
Furniture Bookcase
Office Supplies Appliances
Office Supplies Stationery
Office Supplies Binders
我想将其作为以下菜单在程序中打印出来:
Choose a Sub Catgory:
1:Technology
2:Furniture
3:Office Supplies
Enter a Catgory:2
Choose a Sub Catgory:
1:Chairs
2:Tables
3:Bookcase
Enter a Sub Catgory:1
如果用户在“类别”中选择2(“家具”),则程序将打印出“家具”下的子类别,例如“椅子”,“桌子”和“书柜”。
我可以将类别作为菜单打印出来,但是当用户键入该选项时,该程序将不执行任何操作。
import csv
filePath1 = "codes.csv"
print("Choose a Category : ")
categories = {}
sub_categories = {}
option = 0
with open(filePath1) as csvfile: # open category file
reader = csv.DictReader(csvfile) # dictread file
for row in reader:
categories[row['CATEGORY']] = 0
for key,value in categories.items():
option = option + 1
print("{:>1} : {:<20}".format(option,key))
category = input("Enter Category : ")
if(category == option):
print(option)
答案 0 :(得分:0)
第一个问题是数据的格式。似乎您已经使用空格作为分隔符,这带来了两个问题:
原始数据格式是什么?也许您在复制时将原始数据中的选项卡粘贴到了此处。
从这里开始,我假设各列之间有一个选项卡(\t
)。
运行代码时,出现错误:
Choose a Category :
Traceback (most recent call last):
File "./x.py", line 12, in <module>
categories[row['CATEGORY']] = 0
KeyError: 'CATEGORY'
这是因为csv.DictReader
不了解格式。您没有得到这样的错误很奇怪,我想这是因为您还有其他数据格式。对于制表符分隔的列,我们需要一个附加参数:
with open(filePath1) as csvfile: # open category file
reader = csv.DictReader(csvfile, delimiter='\t') # dictread file
for row in reader:
categories[row['CATEGORY']] = 0
然后,您将在上一节中比较int
与str
的问题。首先将字符串转换为整数来修复它:
try:
category = int(input("Enter Category : "))
if category == option:
print(option)
except ValueError:
print("Try again with a valid category")
最后,仍然存在一个逻辑问题:最后,option
是您拥有的类别数,因此这对我完全没有意义。
怎么样?
#!/usr/bin/env python3
import csv
import sys
filePath1 = "codes.csv"
with open(filePath1) as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
categories = [ row["CATEGORY"] for row in reader ]
# eliminate duplicates, but also destroys the order
categories = list(set(categories))
for i, category in enumerate(categories):
print("{}: {}".format(i, category))
try:
option = int(input("Enter Category: "))
except ValueError:
print("Try again with a valid integer.")
sys.exit(1)
try:
category = categories[option]
print(category)
except IndexError:
print("Value out of bounds.")
sys.exit(1)
# Do something with category...