【发布时间】:2014-07-08 02:50:57
【问题描述】:
如果没有将整个文档包装在单个标签中,xpath 会给我“文档末尾的额外内容”错误。这没问题,我可以将整个东西包装在一个标签中。但是,在我的程序中,您将多次写入该文档,然后进入该文档然后对其进行编辑,这违背了拥有该程序的目的。
这是我写入文档的代码:
def write():
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
post = open('post.txt', 'w')
document = etree.Element('document')
title = raw_input('title>>')
while 1:
message = raw_input('post>>')
post.write(message + '\n')
if '[done]' in message:
tags = raw_input('tags>>')
break
post = open('post.txt', 'r')
postf = post.read()
article = etree.SubElement(document, 'article', title=title, date=st, tags=tags)
article.text = postf
post.close()
with open('postf.txt', 'a') as file:
file.write(etree.tostring(article, pretty_print=True) + '\n')
file.close()
return document, article
这是搜索文档的代码:
if search in command:
query = command.replace(search + ' ', "") #remove precursor
post = open('postf.txt', 'r')
postf = str(post.read())
root = etree.fromstring(postf)
articles = root.xpath('//article[contains(@tags, "%s")]' % query)
for article in articles:
print etree.tostring(article, pretty_print=True)
在调用每个“write()”函数后,我可以在某处添加一个步骤,将整个文档包装在一个标记中吗?
如果需要发布我的完整程序,请告诉我,但我相当确定这是代码中唯一会影响我想要做的事情的部分。如果没有,请发表评论,我将编辑其余部分。谢谢。
【问题讨论】:
标签: python-2.7 xpath xml-parsing lxml