[英]creating a xml file with For Loop in python
我有一個txt文件,其中包含10萬多行,並且我想為每一行創建一個XML樹。 但是所有行都共享相同的根。
這是txt文件:
LIBRARY:
1,1,1,1,the
1,2,1,1,world
2,1,1,2,we
2,5,2,1,have
7,3,1,1,food
所需的輸出:
<LIBRARY>
<BOOK ID ="1">
<CHAPTER ID ="1">
<SENT ID ="1">
<WORD ID ="1">the</WORD>
</SENT>
</CHAPTER>
</BOOK>
<BOOK ID ="1">
<CHAPTER ID ="2">
<SENT ID ="1">
<WORD ID ="1">world</WORD>
</SENT>
</CHAPTER>
</BOOK>
<BOOK ID ="2">
<CHAPTER ID ="1">
<SENT ID ="1">
<WORD ID ="2">we</WORD>
</SENT>
</CHAPTER>
</BOOK>
<BOOK ID ="2">
<CHAPTER ID ="5">
<SENT ID ="2">
<WORD ID ="1">have</WORD>
</SENT>
</CHAPTER>
</BOOK>
<BOOK ID ="7">
<CHAPTER ID ="3">
<SENT ID ="1">
<WORD ID ="1">food</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
我使用元素樹將txt文件轉換為xml文件,這是我運行的代碼
def expantree():
lines = txtfile.readlines()
for line in lines:
split_line = line.split(',')
BOOK.set( 'ID ', split_line[0])
CHAPTER.set( 'ID ', split_line[1])
SENTENCE.set( 'ID ', split_line[2])
WORD.set( 'ID ', split_line[3])
WORD.text = split_line[4]
tree = ET.ElementTree(Root)
tree.write(xmlfile)
好的,代碼正在工作,但是我沒有得到所需的輸出,我得到了以下內容:
<LIBRARY>
<BOOK ID ="1">
<CHAPTER ID ="1">
<SENT ID ="1">
<WORD ID ="1">the</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
<LIBRARY>
<BOOK ID ="1">
<CHAPTER ID ="2">
<SENT ID ="1">
<WORD ID ="1">world</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
<LIBRARY>
<BOOK ID ="2">
<CHAPTER ID ="1">
<SENT ID ="1">
<WORD ID ="2">we</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
<LIBRARY>
<BOOK ID ="2">
<CHAPTER ID ="5">
<SENT ID ="2">
<WORD ID ="1">have</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
<LIBRARY>
<BOOK ID ="7">
<CHAPTER ID ="3">
<SENT ID ="1">
<WORD ID ="1">food</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
如何統一樹的根,而不是得到許多根標簽,而是得到一個根標簽?
另一個可能更簡潔的選擇如下:
from xml.etree import ElementTree as ET
import io
import os
# Setup the test input
inbuf = io.StringIO(''.join(['LIBRARY:\n', '1,1,1,1,the\n', '1,2,1,1,world\n',
'2,1,1,2,we\n', '2,5,2,1,have\n', '7,3,1,1,food\n']))
tags = ['BOOK', 'CHAPTER', 'SENT', 'WORD']
with inbuf as into, io.StringIO() as xmlfile:
root_name = into.readline()
root = ET.ElementTree(ET.Element(root_name.rstrip(':\n')))
re = root.getroot()
for line in into:
values = line.split(',')
parent = re
for i, v in enumerate(values[:4]):
parent = ET.SubElement(parent, tags[i], {'ID': v})
if i == 3:
parent.text = values[4].rstrip(':\n')
root.write(xmlfile, encoding='unicode', xml_declaration=True)
xmlfile.seek(0, os.SEEK_SET)
for line in xmlfile:
print(line)
該代碼的作用是從輸入數據構造ElementTree
並將其作為XML文件寫入到類似文件的對象中。 此代碼將與標准Python xml.etree
包或lxml
。 該代碼已使用Python 3.3進行了測試。
這是使用lxml的建議(已通過Python 2.7測試)。 該代碼也可以輕松地與ElementTree配合使用,但是很難獲得漂亮的打印輸出(有關更多信息,請參見https://stackoverflow.com/a/16377996/407651 )。
輸入文件為library.txt,輸出文件為library.xml。
from lxml import etree
lines = open("library.txt").readlines()
library = etree.Element('LIBRARY') # The root element
# For each line with data in the input file, create a BOOK/CHAPTER/SENT/WORD structure
for line in lines:
values = line.split(',')
if len(values) == 5:
book = etree.SubElement(library, "BOOK")
book.set("ID", values[0])
chapter = etree.SubElement(book, "CHAPTER")
chapter.set("ID", values[1])
sent = etree.SubElement(chapter, "SENT")
sent.set("ID", values[2])
word = etree.SubElement(sent, "WORD")
word.set("ID", values[3])
word.text = values[4].strip()
etree.ElementTree(library).write("library.xml", pretty_print=True)
一種方法是創建完整的樹並進行打印。 我使用以下代碼:
from lxml import etree as ET
def create_library(lines):
library = ET.Element('LIBRARY')
for line in lines:
split_line = line.split(',')
library.append(create_book(split_line))
return library
def create_book(split_line):
book = ET.Element('BOOK',ID=split_line[0])
book.append(create_chapter(split_line))
return book
def create_chapter(split_line):
chapter = ET.Element('CHAPTER',ID=split_line[1])
chapter.append(create_sentence(split_line))
return chapter
def create_sentence(split_line):
sentence = ET.Element('SENT',ID=split_line[2])
sentence.append(create_word(split_line))
return sentence
def create_word(split_line):
word = ET.Element('WORD',ID=split_line[3])
word.text = split_line[4]
return word
然后,用於創建文件的代碼如下所示:
def expantree():
lines = txtfile.readlines()
library = create_library(lines)
ET.ElementTree(lib).write(xmlfile)
如果您不想將整個樹加載到內存中(您提到的行數超過10萬行),則可以手動創建標簽,一次寫一本書,然后添加標簽。 在這種情況下,您的代碼如下所示:
def expantree():
lines = txtfile.readlines()
f = open(xmlfile,'wb')
f.write('<LIBRARY>')
for line in lines:
split_line = line.split(',')
book = create_book(split_line)
f.write(ET.tostring(book))
f.write('</LIBRARY>')
f.close()
我在lxml方面沒有太多經驗,因此可能會有更優雅的解決方案,但是這兩種方法都可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.