Skip to main content
 首页 » 编程设计

python之如何在 lxml 中添加 python 关键字术语作为标记属性

2025年05月04日8www_RR

我正在使用 lxml 基于一些数据构建 XML。

    root = etree.Element('sentences') 
for item in aspectSentenceList: 
    print item 
    sentenceTag = etree.SubElement(root, "sentence", id=item[0]) 
    textTag = etree.SubElement(sentenceTag, "text", text=item[1]) 
    aspectTermsTag = etree.SubElement(sentenceTag, "aspectTerms") 
    for asp in item[2]: 
        aspectTermTag = etree.SubElement(aspectTermsTag, "aspectTerm", term = asp[0], frm = asp[1], to = asp[2]) 

要点在最后一行。共有三个属性,term、from 和to。问题是,python 不允许我将“from”关键字用于除通常导入之外的任何任务。虽然我已经通过使用 frm 而不是 from 完成了临时解决方法,并在以后替换所有此类字符串。但是,如果没有不可靠的黑客攻击,我该如何做到这一点?

请您参考如下方法:

哦,在发布问题后五分钟内就搞定了。文档提到属性是 python 字典。我更新了最后一行:-

aspectTermTag = etree.SubElement(aspectTermsTag, "aspectTerm", {"term":asp[0], "from": asp[1], "to":asp[2]})