通过python发布文本到xml

rqdpfwrv  于 2023-02-01  发布在  Python
关注(0)|答案(1)|浏览(117)

enter image description here '我的代码通过python将文本转换为xml,但是我的程序中有一个bug,无法调试它。它只读取第1行,但是一旦计数器到达第2行,就会出现错误indexerror:out of range。请帮助。如果你看到这个文件,每个条目精确到14行,这14个条目之间用管道(|)分隔符。如果我一直在第一行添加条目,代码工作正常,但当我使用第二行时,它就出错了。
当所有字母都在第一行时,程序的O/P附在图像中。import sys enter image description here当我在第二个角色中移动任何字母时,我的代码给出超出范围错误。无论我输入row [0]、row 1、row [2]等或插入row [i]并每次递增i,堆栈跟踪都是相同的
追溯(最近调用最后调用):文件"c:\Python\Projects\xmlfile.py",第17行,位于客户端。文本=行1索引错误:列表索引超出范围
文本文件的内容为(text.txt):A类|B|C级|D级|E级|F级|G级|高|我|J型|K|L型|男|数量|O型

import csv
from lxml import etree as et

csv.field_size_limit(sys.maxsize)
root = et.Element("Processes")

i = 0

data = []
with open("test.txt") as file:
for row in csv.reader(file, delimiter="|"):
name = et.SubElement(root, "name")
time = et.SubElement(name, "Time")
time.text = row[i]
i += 1
clnt = et.SubElement(name, "Client")
clnt.text = row[i]
i += 1
usr = et.SubElement(name, "User")
usr.text = row[i]
i += 1
txtstat = et.SubElement(name, "textstatus")
txtstat.text = row[i]
i += 1
num = et.SubElement(name, "number")
num.text = row[i]
i += 1
pid = et.SubElement(name, "processid")
pid.text = row[i]
i += 1
prog = et.SubElement(name, "program")
prog.text = row[i]
i += 1
randnum = et.SubElement(name, "randomnumber")
randnum.text = row[i]
i += 1
pidandwp = et.SubElement(name, "processidandwp")
pidandwp.text = row[i]
i += 1
userclnt = et.SubElement(name, "userclient")
userclnt.text = row[i]
i += 1
tid = et.SubElement(name, "transactionid")
tid.text = row[i]
i += 1
add1 = et.SubElement(name, "additional1")
add1.text = row[i]
i += 1
add2 = et.SubElement(name, "additional2")
add2.text = row[i]
i += 1
add3 = et.SubElement(name, "additional3")
add3.text = row[i]
i += 1
add3 = et.SubElement(name, "additional3")
add3.text = row[i]
i += 1
add3 = et.SubElement(name, "additional3")
add3.text = row[i]
i += 1
add3 = et.SubElement(name, "additional3")
add3.text = row[i]
data.append(row)
xml_datas = et.tostring(root, pretty_print=True, xml_declaration=True, encoding="utf-8")
print(xml_datas.decode())`
fruv7luv

fruv7luv1#

这应该会更好地工作,它从文件中读取,不像您使用它的方式那样使用i,并且可以动态地处理任何长度的行。

import csv
from lxml import etree as et

csv.field_size_limit(sys.maxsize)
root = et.Element("Processes")

row_names = [
  'Time',
  'Client',
  'User',
  'number',
  'processid',
  'program',
  'randomnumber',
  'processidandwp',
  'userclient',
  'transactionid',
  'additional1',
  'additional2',
  'additional3'
]

with open("test.txt") as file:
  for row in csv.reader(file, delimiter="|"):
    name = et.SubElement(root, "name")
    for i in range(len(row)):
      node = et.SubElement(name, row_names[i])
      node.text = row[i]

xml_datas = et.tostring(root, pretty_print=True, xml_declaration=True, encoding="utf-8")
print(xml_datas.decode())`

相关问题