2
def citypop():
  import csv                                  
  F = open("Top5000Population.txt")           
  csvF = csv.reader(F)
  D = {}
  with csvF for row in csvF:
      city,state,population = row[0],row[1],row[2] 
      population = population.replace(',','') 
      population = int(population)
      city = city.upper()[:12]
      D[(city, state)] = population
  return D

该函数返回一个以该城市(在该州)的人口为键和作为citypop()值的字典。(city,state)

我不断收到语法错误..我没有正确理解 csv 模块吗?

编辑:谢谢你们的帮助....这应该可以工作,但现在突然间我得到了错误

 for city, state, population in reader(F):       File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode         return codecs.ascii_decode(input, self.errors[0]) UnicodeDecodeError: 'ascii' codec can't decode byte 0xa4 in position 7062: ordinal not in range(128)  

当我运行测试用例时....有什么建议吗?

4

2 回答 2

3

认为您在尝试使用 with 语句时的意思是 - 在这种情况下,文件将在将代码留在其下后立即关闭:

from csv import reader

def citypop():
  D = {}
  with open("Top5000Population.txt") as F:
    for city, state, population in reader(F):
      city = city.upper()[:12]
      D[(city, state)] = int(population.replace(',',''))
  return D

或者:

def citypop():
  with open("Top5000Population.txt") as F:
    return dict(((x.upper()[:12], y), int(z.replace(',', '')) for x, y, z in reader(F))
于 2012-11-08T02:17:17.527 回答
1

我认为您误解了 Python 的with声明。制作第 6 行:

for row in csvF:

应该解决问题。

供参考,该语句与C#中with的语句基本相同;using它声明了您在完成后需要卸载或释放的资源的范围。

于 2012-11-08T02:16:28.040 回答