2014-06-30 124 views
-1

我是新来的编程在Python中,我一直在解析XML文件。解析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 

的changetexts.text返回日志标签,它实际上是日期和修改时间和含有什么已被修改的注释下的全部内容。

但现在的问题出现了:我需要文件日志的前10行。但我实际上检索了日志文件的所有内容(比如2000行左右)。

任何人都可以建议我的概念,我应该用来访问日志的前10行。 代码片段也将有所帮助。

注意:日志标记中没有标记。

标签的看法是这样的:

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

</log> 
+0

你是什么意思 “十强”?你的意思是_first十行,还是其他一些标准? –

+0

其实它的前10行。对不起,我没有明确指定它 – sankar

回答

1

使用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 !! 
+0

谢谢你的作品 – sankar