2 天前,我第一次接触 Python(以及一般的编程)。今天我被困住了。我花了几个小时试图找到一个我怀疑是一个如此微不足道的问题的答案,没有其他人被困在这里:)
老板要我手动清理巨大的 .xml 文件,使其更易于阅读。我正在尝试创建一个脚本来为我做这件事。以下是 .xml 文件的示例以及我想要的输出。
输入(文件.xml):
<IssueTracking>
<Issue>
<SequenceNum>123</SequenceNum>
<Subject>Subject of Ticket 123</Subject>
<Description>Line 1 in Description field of Ticket 123.
Line 2 in Description field of Ticket 123.
Line 3 in Description field of Ticket 123.</Description>
</Issue>
<Issue>
<SequenceNum>124</SequenceNum>
<Subject>Subject of Ticket 124</Subject>
<Description>Line 1 in Description field of Ticket 124.
Line 2 in Description field of Ticket 124.
Line 3 in Description field of Ticket 124.</Description>
</Issue>
</IssueTracking>
期望的输出:
123 Subject of Ticket 123
Line 1 in Description field of Ticket 123.
Line 2 in Description field of Ticket 123.
Line 3 in Description field of Ticket 123.
124 Subject of Ticket 124
Line 1 in Description field of Ticket 124.
Line 2 in Description field of Ticket 124.
Line 3 in Description field of Ticket 124.
这是我到目前为止所得到的。
with open(File.xml, 'r') as SourceFile: # Opens the file
while 1: # Keep going through the file to the end
SourceFileLine = SourceFile.readline() # Saves lines of the source file
if not SourceFileLine: # Skip empty lines
break
SourceFileLine = SourceFileLine.strip() # Strips the whitespace
if "<SequenceNum>" in SourceFileLine:
SequenceNum = SourceFileLine[13:-14] # Trims the tags, saves the field.
continue
if "<Subject>" in SourceFileLine:
Subject = SourceFileLine[9:-10]
continue
#if "<Description>" in SourceFileLine:
# last_pos = SourceFile.tell()
# while "</Description>" not in SourceFileLine:
# SourceFile.seek(last_pos)
# ?????
#
# Description = Description[22:]
# continue
if "</Issue>" in SourceFileLine:
print(SequenceNum, end = "\t")
print(Subject)
# print(Description)
print("\n")
我一直在识别标签之间的这三行并将其保留<Description>
为一个我可以打印的字符串,然后再继续输入源文件。现在已经扫描了几十个文件行读取循环的其他示例,我怀疑我需要标记到达目标字段的点并在文件中的该点嵌套另一个读取循环。但是我还没有找到另一个这样做的例子,所以我认为我缺少一些基本的东西或者有更好的方法。提前感谢您的帮助!