因此,我目前面临的问题是将文本文件转换为xml文件。 文本文件将采用这种格式。

Serial Number:      Operator ID:  test  Time:  00:03:47 Test Step 2      TP1:  17.25    TP2:  2.46
Serial Number:      Operator ID:  test  Time:  00:03:47 Test Step 2      TP1:  17.25    TP2:  2.46

我想将其转换为以下格式的xml:

<?xml version="1.0" encoding="utf-8"?>
<root>
 <filedata>
 </serialnumber>
 <operatorid>test</operatorid>
 <time>00:00:42 Test Step 2</time>
 <tp1>17.25</tp1>
 <tp2>2.46</tp2>
 </filedata>
...
</root>

我正在使用像这样的代码将以前的文本文件转换为xml ...但是现在我在拆分行时遇到问题。

import xml.etree.ElementTree as ET
import fileinput
import os
import itertools as it

root = ET.Element('root')
with open('text.txt') as f:
    lines = f.read().splitlines()
celldata = ET.SubElement(root, 'filedata')
for line in it.groupby(lines):
    line=line[0]
    if not line:
        celldata = ET.SubElement(root, 'filedata')
    else:
        tag = line.split(":")
        el=ET.SubElement(celldata,tag[0].replace(" ",""))
        tag=' '.join(tag[1:]).strip()
        if 'File Name' in line:
            tag = line.split("\\")[-1].strip()
        elif 'File Size' in line:
            splist =  filter(None,line.split(" "))
            tag = splist[splist.index('Low:')+1]
            #splist[splist.index('High:')+1]
        el.text = tag
import xml.dom.minidom as minidom
formatedXML = minidom.parseString(
                          ET.tostring(
                                      root)).toprettyxml(indent=" ",encoding='utf-8').strip()

with open("test.xml","wb") as f:
    f.write(formatedXML)

我在stackoverflow中看到了类似的问题 " 将Python文本文件转换为xml " 但问题是我无法将其更改为.csv格式,因为此文件是由特定计算机生成的。 如果有人知道如何解决,请提供帮助。 谢谢。

分析解答

这是分割线的更好方法。

请注意,从技术上讲text变量将是您的.txt文件,并且我有意对其进行了修改,以便我们对输出有更大的了解。

from collections import OrderedDict
from pprint import pprint

# Text would be our loaded .txt file.
text = """Serial Number:  test    Operator ID:  test1  Time:  00:03:47 Test Step 1      TP1:  17.25    TP2:  2.46
Serial Number:      Operator ID:  test2  Time:  00:03:48 Test Step 2      TP1:  17.24    TP2:  2.47"""

# Headers of the intended break-points in the text files.
headers = ["Serial Number:", "Operator ID:", "Time:", "TP1:", "TP2:"]

information = []

# Split our text by lines.
for line in text.split("\n"):

    # Split our text up so we only have the information per header.
    default_header = headers[0]
    for header in headers[1:]:
        line = line.replace(header, default_header)
    info = [i.strip() for i in line.split(default_header)][1:]

    # Compile our header+information together into OrderedDict's.
    compiled_information = OrderedDict()
    for header, info in zip(headers, info):
        compiled_information[header] = info

    # Append to our overall information list.
    information.append(compiled_information)

# Pretty print the information (not needed, only for better display of data.)
pprint(information)

输出:

[OrderedDict([('Serial Number:', 'test'),
              ('Operator ID:', 'test1'),
              ('Time:', '00:03:47 Test Step 1'),
              ('TP1:', '17.25'),
              ('TP2:', '2.46')]),
 OrderedDict([('Serial Number:', ''),
              ('Operator ID:', 'test2'),
              ('Time:', '00:03:48 Test Step 2'),
              ('TP1:', '17.24'),
              ('TP2:', '2.47')])]

这种方法的通用性应该比您当前编写的方法更好,并且代码的思想是我从另一个项目中保存的。我建议您仔细阅读代码并理解其逻辑。

从这里,您应该能够遍历information列表并创建您的自定义.xml文件。我建议您也检查dicttoxml,因为这可能使您的生活更轻松。

关于您的代码,请记住:分解基本任务比将所有任务合并为一件要容易得多。通过在拆分txt文件时尝试创建xml文件,您创建了一个怪兽,当怪兽反叛时,很难解决。取而代之的是,一次--一步一步创建"checkpoints",您​​可以100%完成某些工作,然后继续执行下一个任务。