2014-12-19 2 views
-3

.txt 파일을 읽는 방법을 알고 싶었고 출력은 .xml 형식이어야합니다..txt를 읽고 python3.2에서 .xml을 출력하십시오.

나는

 Paper 1/White Spaces are included 
Single Correct Answer Type 

1. Text of question 1 
    a) Option 1.a b) Option 1.b 
    c) Option 1.c d) Option 1.d 

2. Text of question 2 
    a) This is an example of Option 2.a 
    b) Option 2.b has a special char α 
    c) Option 2.c 
    d) Option 2.d 

3. Text of question 3 
    a) Option 3.a can span multiple 
    lines. 
    b) Option 3b 
    c) Option 3c 
    d) Option 3d 

등의 입력 파일이 내 코드 :

from lxml import etree 
import csv 

root = etree.Element('data') 
#f = open('input1.txt','rb') 
rdr = csv.reader(open("input1.txt",newline='\n')) 
header = next(rdr) 
for row in rdr: 
    eg = etree.SubElement(root, 'eg') 
    for h, v in zip(header, row): 
     etree.SubElement(eg, h).text = v 

f = open(r"C:\temp\input1.xml", "w") 
f.write(etree.tostring(root)) 
f.close() 

내가 좋아하는 오류를 받고 있어요 :

Traceback (most recent call last): 
    File "E:\python3.2\input1.py", line 11, in <module> 
    etree.SubElement(eg, h).text = v 
    File "lxml.etree.pyx", line 2995, in lxml.etree.SubElement (src\lxml\lxml.etree.c:69677) 
    File "apihelpers.pxi", line 188, in lxml.etree._makeSubElement (src\lxml\lxml.etree.c:15691) 
    File "apihelpers.pxi", line 1571, in lxml.etree._tagValidOrRaise (src\lxml\lxml.etree.c:29249) 
ValueError: Invalid tag name ' Paper 1' 

그리고 나는 그것이 흰색을 고려할 공백도. 파이썬 3.2를 사용하고 있습니다. 어떤 제안?

+0

가능한 중복 http://stackoverflow.com/questions/18739501/python-text-을 파일 대 XML) –

답변

1

이 정보를 txt 파일에서 읽고 개체 클래스로 구성한 다음이를 직렬화 할 수 있습니다.

/직렬화 해제하는 방법 : http://code.activestate.com/recipes/577266-xml-to-python-data-structure-de-serialization/

예 :

f = open('file.txt') 
lines = f.readlines() 
f.close() 

#do something to orginize these lines into objects. 

xmlStrings = [serialize(pythonObj) for pythonObj in txtInfoObjs] 

g = open('file.xml') 
g.write(xmlStrings[0]) 
g.close() 
[XML로 파이썬 텍스트 파일 (의
관련 문제