Python处理US机场CSV文件时循环在name_function中卡顿求助
处理美国机场CSV生成缩写时的运行错误
我正在处理us-airports.csv文件,该文件包含美国约30000个机场的名称与城市信息,目标是生成机场名称和城市的缩写。我的代码如下:
file_in = open("us-airports.csv", "r", encoding="utf-8") file_out = open("output1.csv", "w") row = file_in.readlines() city_abb="" name_abb = "" # 定义生成缩写的函数 def name_function(name): global name_abb name=name.split() for t in range(len(name)): if t < 2: name_abb = str(name[0][0]+name[1][0]) else: name_abb = str(name[0][0]+name[1][0]+name[2][0]) name_abb = name_abb.upper() return(name_abb) def city_function(city): global city_abb letters=city[:3] city_abb=letters.upper() return(city_abb) # 循环处理每一行 for i in range(len(row)): row[i] = row[i].strip() items = row[i].split(",") city_function(items[1]) name_function(items[0]) # 写入输出文件 file_out.write(f"{items[0]},{items[1]},{city_abb},{name_abb}\n") # 打印调试信息 print(i+1) print(f"{items[0]},{items[1]},{city_abb},{name_abb}\n") file_out.close() file_in.close() print("done")
程序运行到第1454次循环时,在name_function的以下代码行触发错误:
if t < 2: name_abb = str(name[0][0]+name[1][0])
经查看对应的CSV行,发现该行的机场名称是无空格的单词语句,调用split()后得到的列表仅含1个元素,此时尝试访问name[1]会触发索引越界,导致程序卡住。
内容的提问来源于stack exchange,提问作者Matthew Boisseau
相关产品推荐
相关产品推荐

