gpt4 book ai didi

Python newb : What's preventing this function from printing?

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:02 25 4
gpt4 key购买 nike

背景

我用 python 的工作不多,但我想用它为我生成一些重复的 XML。现在,我只想解析 CSV,然后将这些值传递到 XML 节中。

有一个问题:在编写 XML 之前,我需要重写一些 CSV。我有一些 if 语句来为我处理这个问题,我决定通过将它移到一个单独的函数中来减少困惑。

这就是我的问题出现的地方。我的 writeTypes 函数似乎按预期工作但是当我返回重写的 csvDict 实例时,我无法再打印值。

显然我遗漏了一些东西,可能很简单 - 但是什么?脚本下面有评论。

脚本

import csv

def parseCSV(vals):

# read the csv

dictReader = csv.DictReader(open(vals, 'rb'), fieldnames=['name', 'type', 'nullable', 'default', 'description', '#'], delimiter=',', quotechar='"')

# some repetitive xml; I will finish this portion later...

stanza = '''
<var name="{0}" precision="1" scale="None" type="{1}">
<label>{2}</label>
<definition><![CDATA[@{3}({4})]]></definition>
</var>'''

# a function that simply writes new values to dictionary entries

writeTypes(dictReader)

# I'm confused here - nothing is printed to the console.
# If i comment my 'writeTypes function, prints as expected

for i in dictReader:
print i
print i['type']


# function to rewrite 'types' key in dictionary set
def writeTypes(d):

for i in d:
if i['type'] == 'text':
i['type'] = 't'
elif i['type'] == 'boolean':
i['type'] = 'l'
elif i['type'] == 'double precision':
i['type'] = 'd'
elif i['type'] == 'integer':
i['type'] = 'i'
else:
i['type'] = i['type']

# unsurprisingly, this function does seem to print the correct values
print i

# it seems as though there's something wrong with this return statement...
return d

示例 CSV

(从 .gov 网站提取的公共(public)数据)

Name,Type,Nullable,Default,Description,#
control,text,true,,,1,false
flagship,boolean,true,,,1,false
groupid,text,true,,,1,false
hbcu,text,true,,,1,false
hsi,text,true,,,1,false
iclevel,text,true,,,1,false
landgrnt,text,true,,,1,false
matched_n_00_10_11,boolean,true,,,1,false
matched_n_05_10_6,boolean,true,,,1,false
matched_n_87_10_24,boolean,true,,,1,false
name,text,true,,,1,false
name_short,text,true,,,1,false
school,text,true,,,1,false
sector,text,true,,,1,false
sector_revised,text,true,,,1,false
top_50,boolean,true,,,1,false
virginia,boolean,true,,,1,false

最佳答案

dictReader 是一个迭代器,一旦它读完 CSV 文件,它就会耗尽:进一步的迭代将不会做任何事情。

解决此问题的方法是在 writeTypes 中创建一个新的字典列表,这样您就可以在此处而不是在原始列表中分配值。然后您可以返回该列表,并在 main 函数中对其进行迭代。

关于Python newb : What's preventing this function from printing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24290698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com