【问题标题】:Printing elements from csv file using raw_input使用 raw_input 从 csv 文件打印元素
【发布时间】:2015-05-23 14:35:02
【问题描述】:

如何使用 raw_input 从 csv 文件中打印元素?

代码:

import csv

inputYear = raw_input('Please enter the year: ')
inFile = open('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)

# According to informaiton in 'dict',  print (name, count) sorted by 'name' in alphabetical order         

print("Print boy names... ")    
inFile.close()

期望的输出:

2010 年流行的男孩名字是: 艾丹112 艾登168 亚历克斯 93

【问题讨论】:

  • 请将其标记为 python2.7(?),因为 Python 3 没有 raw_input()
  • 你能提供文件内容的样本吗?
  • 2010,约翰,124,男 /n 2010,艾米,111,女
  • 文件包含男孩名和女孩名,我只需要男孩名和他们的人数
  • 抱歉输出不是 .."male" 和 ..."female";女性和男性被交换为“男孩”和“女孩”,因此条件是搜索所有“男孩”的名字......

标签: python-2.7 csv raw-input


【解决方案1】:

你可以试试这个:

inputYear = raw_input('Please enter the year: ')

file1 = open('babyQldAll.csv','r')
fileContent = file1.readlines()
fileRows = fileContent[0].split("\\n")

dict = {}
for row in fileRows:
    year = row.split(',')[0].strip()
    name = row.split(',')[1].strip()
    count = row.split(',')[2].strip()
    gender = row.split(',')[3].strip()
    if (year == inputYear) and (gender == 'Boy'):
        dict[name] =  count
odDict = sorted(dict.items())
str = ''
for i in odDict:
    str = str + i[0] + ' ' + i[1] + ' '

print('Popular boy names in year '+ inputYear + ' are: ' + str)
file1.close()

【讨论】:

  • 它正在为我提供输出。你用的是哪个python版本? 2.7对吗?
  • 你能把print fileRows 放在dict= {} 的上方,把print year, gender 放在if (year == inputYear) and (gender == 'Boy'): 的上方,让我知道你在输出中得到了什么吗?
  • 输出:` ['2010, Ruby, 440, Girl\n] 2010 Girl `
  • 您的文件似乎只有一行,而且性别也有Girl。并且该脚本将仅输出用户给出的年份的Boys。因此,没有输出。
  • 没有可以添加到原始代码中的函数吗?
猜你喜欢
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多