【问题标题】:Python return error while writing data into file(Python 2.7)将数据写入文件时 Python 返回错误(Python 2.7)
【发布时间】:2023-03-03 17:33:02
【问题描述】:

我正在使用 python mini-Dom 模块解析 XML 文件。将数据写入文件时会出现 Unicode Encode Error: 'ASCII' codec can't encode characters in position 0-3: ordinal not in range(128) 之类的错误。但是在命令行上输出打印完美请告诉我解决方案。

我的 XML 文件是:

   <?xml version="1.0"?>
    <Feature>
        <Word Root  ="ਨੌਕਰ-ਚਾਕਰ">
            <info Inflection  ="ਨੌਕਰਾਂ-ਚਾਕਰਾਂ">
        <posinfo gender  ="Masculine" number  ="Plural" case  ="Oblique" />

                </info>
        </Word>
                </Feature>

我的python代码是:

import sys

from xml.dom import minidom

file=open("npu.txt","w+")
doc = minidom.parse("NPU.xml")
word = doc.getElementsByTagName("Word")
for each in word:
    # print "root"+each.getAttribute("Root")
    file.write(each.getAttribute("Root")+"\n")
    hh=each.getElementsByTagName("info")

    for each1 in hh:
        # print "inflection"+each1.getAttribute("Inflection")
        file.write(each1.getAttribute("Inflection")+"\t")

        vv=each1.getElementsByTagName("posinfo")
        for each2 in vv:
            # print each2.getAttribute("gender")
            # print each2.getAttribute("number")
            # print each2.getAttribute("case")
            file.write( each2.getAttribute("gender")+",")
            file.write( each2.getAttribute("number")+",")
            file.write(each2.getAttribute("case"))
        file.write("\n")
    file.write("--------\n")

【问题讨论】:

    标签: python xml minidom


    【解决方案1】:
    encode data while writing-
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    file=open("npu.txt","w+") 
    file.write("ਨੌਕਰ-ਚਾਕਰ")
    

    【讨论】:

      【解决方案2】:

      问题不在于您解析 XML 的方式,这是一个编码问题。

      该错误是由您的文本编码 (UTF-8) 引起的。 您正在尝试将文本编写为不包含您正在使用的字符的 ASCII。

      尝试使用如下编解码器:

      import codecs
      
      file = codecs.open("npu.txt", "w+", "utf-8")
      file.write("ਨੌਕਰ-ਚਾਕਰ".decode('utf-8'))
      file.close()
      

      编辑:

      您还可以将默认编码设置为 UTF-8 添加特殊注释 # -*- coding: UTF-8 -*- 在 python 源代码的开头。默认编码为 ASCII(7 位)。 请注意,Python 标识符仍然仅限于 ASCII 字符。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-15
        • 1970-01-01
        • 2014-01-21
        • 1970-01-01
        相关资源
        最近更新 更多