在分析xml文件时编辑文本

2024-09-30 18:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python编程新手,一直致力于解析xml文件。你知道吗

我已经使用了xml解析器,并且能够解析文件。你知道吗

 import xml.etree.ElementTree as ET
tree = ET.parse('hi.xml')

root = tree.getroot()
count = 0
for changetexts in root.findall('log'):
    temp = changetexts.text

那个更改文本.text返回日志标记下的全部内容,这些内容实际上是修改的日期和时间,以及包含已修改内容的注释。你知道吗

但现在问题来了:我需要文件日志的前10行。但实际上我检索了日志文件的所有内容(比如说大约2000行)。你知道吗

有人能告诉我应该用什么概念来访问日志的前10行吗。 代码片段也会很有帮助。你知道吗

注意:日志标记中没有标记。你知道吗

标记的视图如下所示:

<log>
date_1            time_1             comment_1
date_2            time_2             comment_2
date_3            time_3             comment_3

</log>

Tags: 文件text标记logtree内容datetime
1条回答
网友
1楼 · 发布于 2024-09-30 18:28:27

使用splitlines()

import xml.etree.ElementTree as ET
tree = ET.parse('hi.xml')

root = tree.getroot()
count = 0
for changetexts in root.findall('log'):
    temp = changetexts.text
    lines =  temp.splitlines()
    tenlines = lines[0:10]
    print (len(tenlines)) # Should be 10, use tenlines variable as you wish !!

相关问题 更多 >