Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python将XML格式的文本写入输出文件_Python_Xml - Fatal编程技术网

用Python将XML格式的文本写入输出文件

用Python将XML格式的文本写入输出文件,python,xml,Python,Xml,我在将下面的XML写入输出文件时遇到问题 <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?> <root> <document> <sentences> <sentence id="1"> <tokens> <token id="

我在将下面的XML写入输出文件时遇到问题

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?>
<root>
 <document>
  <sentences>
   <sentence id="1">
    <tokens>
     <token id="1">
      <word>
       Pusheen
      </word>
      <CharacterOffsetBegin>
       0
      </CharacterOffsetBegin>
      <CharacterOffsetEnd>
       7
      </CharacterOffsetEnd>
      <POS>
       NNP
      </POS>
     </token>
    </tokens>
   </sentence>
  </sentences>
 </document>
</root>
但是,我得到了下面的错误

AttributeError: 'str' object has no attribute 'write' 

我不必在这里构建XML,因为我已经拥有XML格式的数据。我只需要将其写入XML文件

假设
是您的XML,它是一个字符串。您可能需要以下内容:

with open("person.xml", "w", encoding="unicode") as outfile:
  outfile.write(tree)
(最好将
一起用于文件;之后会自动关闭它们)


由于
tree
是一个字符串,因此无法对其进行写入,因此导致此错误。

我建议使用
lxml
模块首先检查格式,然后将其写入文件。我注意到有两个元素具有相同的id,这引起了我的注意。它不会在XML中标记错误,但可能会在HTML页面上造成问题,因为每个id都应该是唯一的
下面是执行我上面描述的操作的简单代码:

from lxml import etree
try:
    root = etree.fromstring(your_xml_data) # checks XML formatting, returns Element if good
    if root is not None:
        tree = etree.ElementTree(root)  # convert the Element to ElementTree
        tree.write('person.xml')        # we needed the ElementTree for writing the file
except:
    'Oops!'

非常感谢您的投入。尽管修改很少,但它仍然有效。使用open(“output.xml”,“w”)作为outfile:outfile.write(pretty_bs)您可能需要
encoding=“utf-8”
如果您要走这条路,您可能需要
open('person.xml','w')。write(tree)
谢谢您的建议。将使用lxml检查格式。
from lxml import etree
try:
    root = etree.fromstring(your_xml_data) # checks XML formatting, returns Element if good
    if root is not None:
        tree = etree.ElementTree(root)  # convert the Element to ElementTree
        tree.write('person.xml')        # we needed the ElementTree for writing the file
except:
    'Oops!'