簡體   English   中英

使用%字符串格式時,值錯誤不受支持的格式字符““”

[英]Value Error unsupported format character '"' when using % string formatting

我正在嘗試使用字符串格式將傳入的CSV轉換為XML。 我收到以下錯誤:

ValueError: unsupported format character '"' (0x22) at index 36

我了解我在不應該但找不到該位置的地方使用了“。模板內的“應全部封裝在“””……“””中,而我看不到任何腳本中的其他位置。

誰能建議我哪里出問題了?

import csv
import sys


def csvDict(csvRow):
    dict = {'Name': csvRow[0], 'p1t': csvRow[1], 'p1l': csvRow[2], 'p2t': csvRow[3], 'p2l': csvRow[4],
            'outputWidth': csvRow[5], 'sourceTop': csvRow[6], 'sourceLeft': csvRow[7], 'sourceWidth': csvRow[8],
            'sourceHeight': csvRow[9]}
    return dict


# Get CSV File from the argument
csvFile = csv.reader(open(sys.argv[1], 'rt'))

# Convert CSV Into list for Processing
csvList = list(csvFile)

# Setup XML Variables Dictionary
outputVars = csvDict(csvList[0])

# Confirm Dictionary contains the right data
print outputVars


# XML Format Template
mapTemplate = """<map type="map2dpanel" name="%(Name)" width="%(outputWidth)" >
        <point id="1" top="%(p1t)" left="%(p1l)" /><point id="2" top="%(p2t)" left="%(p2l)" />
        <source image="current source" top="%(sourceTop)" left="%(sourceLeft)" width="%(sourceWidth)" height="%(sourceHeight)" />
    </map>
"""

print mapTemplate % outputVars

您忘記指定占位符的類型。 Python需要%(name)s%(name)d任何其他受支持的類型

取而代之的是,Python發現下一個字符"不是有效的格式字符:

name="%(Name)"
#     -------^

由於您是從CSV文件中讀取值,因此它們都是字符串。 s字符添加到模板占位符:

mapTemplate = """\
    <map type="map2dpanel" name="%(Name)s" width="%(outputWidth)s" >
        <point id="1" top="%(p1t)s" left="%(p1l)s" /><point id="2" top="%(p2t)s" left="%(p2l)s" />
        <source image="current source" top="%(sourceTop)s" left="%(sourceLeft)s" width="%(sourceWidth)s" height="%(sourceHeight)s" />
    </map>
"""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM