首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Python‘TypeError:__new__()只接受7个参数(2个给定)’

Python‘TypeError:__new__()只接受7个参数(2个给定)’
EN

Stack Overflow用户
提问于 2013-07-29 02:34:49
回答 1查看 5.2K关注 0票数 0

我已经编写了一个程序(在一些帮助下),它从csv中提取数据并创建一个kml,以便在Google中查看。效果不错..。我现在试着修改它以处理不同的数据,我不断地发现这个错误-

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
TypeError: __new__() takes exactly 7 arguments (2 given)

我不知道它意味着什么,因为我几乎没有改变最初的程序,只是名称元组部分,all_locations = (location_info(*line[0:5]) for line in csv_reader) (以反映只有6个名称元组条目),并且修改了KML的'ExtendedData‘部分。

我在这里挠头..。有什么想法吗?

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-29 02:54:46

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

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

请注意,line[:5]将具有相同的结果,并且每个CSV结果行的5个元素切片(而不是6,停止值不包括在内);您还在对行进行切片,而不是对CSV文件进行切片(您似乎有这样的印象:切片line只会导致6个名称元组对象)。

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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=';')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17921812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文