0

我编写了一个程序(在一些帮助下),它从 csv 中提取数据并创建一个用于在 Google 地球中查看的 kml。它工作正常......我现在尝试修改它以使用不同的数据,但我不断收到这个错误 -

TypeError: __new__() takes exactly 7 arguments (2 given)

我无法弄清楚它的含义,因为我对原始程序的更改很少,只是命名元组部分all_locations = (location_info(*line[0:5]) for line in csv_reader)(以反映只有 6 个命名元组条目)并修改了 KML 的“扩展数据”部分。

我在这里摸不着头脑......有什么想法吗?

from Tkinter import *
from tkFileDialog import askopenfilename
import Tkconstants
from collections import namedtuple
import csv
import os


master = Tk()
master.title("KML creation")
path = ""
counter = 0

def counter_label(label):
    def count():
        global counter
        counter += 1
        label.config(text="Loading: " + str(counter))
        label.after(1000, count)
    count()

def getPath():
    options = {}
    options['defaultextension'] = '.csv'
    #options['filetypes'] = ('Comma Separated Values', '*.csv') #only windows
    options['initialdir'] = 'C:\\Python27'
    options['initialfile'] = 'myfile.csv'
    options['title'] = 'Choose File for KML creation...'
    Tk().withdraw()
    path = askopenfilename(**options)
    counter_label(l)
    print(path)

    location_info = namedtuple('location_info', 'NAME, DATE, TIME, LAT, LON, DESCRIPTION')
    input_filename = path
    output_filename = "mapppp.kml"

    with open(input_filename, 'r') as input_file:
        csv_reader = csv.reader(input_file, delimiter=';')
        print next(csv_reader)  # gets rid of the header line
        all_locations = (location_info(*line[0:5]) for line in csv_reader)  # the slicing is due to the trailing ;

        with open(output_filename, 'w') as output_file:
            write_header(output_file)
            for location in all_locations:
                output_file.write(get_kml(location))
            write_footer(output_file)

            for files in os.listdir("."):
                if files.endswith(".csv"):
                    print files

    print ("File Created. ")
    output_file.close()
    input_file.close()


def write_header(output_file):
    output_file.write(
    """<?xml version='1.0' encoding='UTF-8'?>\n
<kml xmlns='http://www.opengis.net/kml/2.2'>\n
<Folder>\n
    <name>  </name>\n""")


def get_kml(location_info):
    return"""

<Folder>
<ScreenOverlay>
    <name>Absolute Positioning: Top left</name>
    <Icon>
      <href>http://a2.twimg.com/profile_images/1345561985/_sq_normal.png</href>
    </Icon>
    <overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>
    <screenXY x="0" y="1" xunits="fraction" yunits="fraction"/>
    <rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
    <size x="0" y="0" xunits="fraction" yunits="fraction"/>
  </ScreenOverlay>
<name> {CID} </name>
    <Placemark>
     <Style id="sn_16">
     <LabelStyle>
                    <color>ff0000ff</color>
                    <colorMode>normal</colorMode>
                    <scale>1</scale>
                </LabelStyle>
      <IconStyle>
          <Icon>
            <href>http://www.sytech-consultants.com/images/GE%20KML/Circle/4.png</href>
            <scale>1.0</scale>
          </Icon>    
      </IconStyle>
    </Style>
    <name> {REF} ({DESCRIPTION}) </name>
        <ExtendedData>
            <Data name='Ref'>
                <value>
                    {NAME}
                </value>
                <Data name='Date'>
                <value>
                    {DATE}
                </value>
            </Data>
            <Data name='Time'>
                <value>
                    {TIME}
                </value>
            </Data>
        </ExtendedData>
        <Point>
        <altitudeMode>relativeToGround</altitudeMode>
           <extrude> 1 </extrude>
            <coordinates>{LON},{LAT}, 25 </coordinates>
        </Point>
    </Placemark>
</Folder>""".format(**location_info._asdict())



def write_footer(output_file):
    output_file.write(
    """
</Folder>
</kml>""")

button_opt = {'fill': Tkconstants.BOTH, 'padx': 25, 'pady': 25}
b = Button(master, text="Choose a file for KML creation", command=getPath)
l = Label(master)
l.pack()
b.pack(**button_opt)
master.mainloop()

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
    return self.func(*args)
  File "C:\Users\zackj\Desktop\ZacksKMLCreator.py", line 45, in getPath
    for location in all_locations:
  File "C:\Users\zackj\Desktop\ZacksKMLCreator.py", line 41, in <genexpr>
    all_locations = (location_info(*line[0:7]) for line in csv_reader)  # the slicing is due to the trailing ;
TypeError: __new__() takes exactly 7 arguments (2 given)
4

1 回答 1

1

您正在尝试location_info从仅包含列的 CSV 行创建一个 namedtuple 对象。

Python 切片允许您切片超出序列的长度;line[0:5]在仅包含 2 个值的行上返回仅包含两个值的新列表。这是您的 CSV 文件中的错误;您需要验证每一行是否有足够的列。

请注意,这将具有相同的结果,并且将每个 CSV 结果行的5 个line[:5]元素切片(不是 6 个,不包括停止值);您也在切片row,而不是 CSV 文件(您似乎认为切片只会产生 6 个 namedtuple 对象)。line

在任何情况下,您可能希望直接使用字典csv.DictReader()来进行模板格式设置。该工具具有额外的csv.DictReader

location_info = namedtuple('location_info', 'NAME, DATE, TIME, LAT, LON, DESCRIPTION')
input_filename = path
output_filename = "mapppp.kml"

with open(input_filename, 'r') as input_file:
    csv_reader = csv.reader(input_file, delimiter=';')
于 2013-07-29T10:54:46.277 回答