【问题标题】:invalid python syntax in my 'for' loop我的“for”循环中的python语法无效
【发布时间】:2012-11-08 02:12:11
【问题描述】:
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)  

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

【问题讨论】:

  • 解释器说语法错误在哪里?
  • 它突出显示第 6 行中的“for”一词
  • 那一行不需要with csvF。它应该只是for row in csvF:
  • 你想要的是with open("Top5000Population.txt") as F:

标签: python csv syntax


【解决方案1】:

当您尝试使用 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))

【讨论】:

    【解决方案2】:

    我认为你误解了 Python 的with statement。制作第 6 行:

    for row in csvF:
    

    应该解决问题。

    作为参考,with 语句与 C# 中的using 语句基本相同;它声明了一个资源的范围,当你完成它时你需要卸载或释放它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 2018-10-30
      相关资源
      最近更新 更多