【发布时间】:2015-12-09 08:30:14
【问题描述】:
我需要编写一个程序,它接受用户输入的年份并从 CSV 文件中读取信息,然后将结果导出到屏幕上。 csv 源文件格式为:year, name, count, gender,导出结果为boy only,格式为Name Count,按字母顺序排列。
输入文件:
2010,Ruby,440,Female
2010,Cooper,493,Male
输出:
Please enter the year: 2010
Popular boy names in year 2010 are:
Aidan 112
运行程序时出现错误:
Please enter the year: 2014
Traceback (most recent call last):
File "E:\SIT111\A1\printBoynameTPL.py", line 26, in <module>
year, name, count, gender = row
ValueError: need more than 0 values to unpack
这是我的代码:
'''
This program accepts a year as input from a user and print boys' information of the year. The output should be sorted by name in alphabetical order.
Steps:
1. Receive a year from a user
2. Read CSV files:
Format: year, name, count, gender
3. Display popular boy names on the screen:
Format: Name Count
'''
import csv
inputYear = raw_input('Please enter the year: ')
inFile = open('output/babyQldAll.csv', 'rU')
cvsFile = csv.reader(inFile, delimiter=',')
dict = {}
for row in cvsFile:
year, name, count, gender = row
if (year == inputYear) and (gender == 'Boy'):
dict[name] = count
print('Popular boy names in year %s are:' % inputYear)
# +++++ You code here ++++
# According to informaiton in 'dict', print (name, count) sorted by 'name' in alphabetical order
sortedName = shorted(dict.keys())
for name in sortedName:
print(name, dict[name])
print("Print boy names... ")
inFile.close()
我编辑了一下:
for row in cvsFile:
if row:
year, name, count, gender = row
if (year == inputYear) and (gender == 'Male'):
dict[name] = count
print('Popular boy names in year %s are:' % inputYear)
# +++++ You code here ++++
# According to informaiton in 'dict', print (name, count) sorted by 'name' in alphabetical order
sortedName = sorted(dict.keys())
for name in sortedName:
print(name,dict[name])
print("Print boy names... ")
我做错了吗?缩进还是……?
结果:
>>>
Please enter the year: 2013
Popular boy names in year 2013 are:
Print boy names...
>>>
【问题讨论】:
标签: python sorting csv dictionary