【问题标题】:TypeError: write() argument must be str, not EntityAnnotationTypeError: write() 参数必须是 str,而不是 EntityAnnotation
【发布时间】:2019-01-08 14:42:20
【问题描述】:

我正在使用 Google vision api 从图像中提取文本,并且我还想将此文本存储在 .txt 文件中。

每当我使用f.write(text.description) 时,我都会得到:

UnicodeEncodeError

f.write(text) 它给了我:

TypeError: write() 参数必须是 str,而不是 EntityAnnotation

f.write(text.description.encode("utf-8")) 给我:

TypeError: write() 参数必须是 str,而不是字节。

【问题讨论】:

    标签: python


    【解决方案1】:

    您正在尝试编写 EntityAnnotation 类型的变量,它是 Json 对象而不是 str。查看EntityAnnotation - Google Cloud Vision,在位置选项卡上,您可以了解结构是如何制作的。可能您正在尝试编写一些分配在其中的信息。

    请记住,您可以通过将其设为字符串 str(json_objt) 或使用来编写整个对象 json.dumps(json_obj) 以便将 json_obj 序列化为格式为 str 的 JSON。

    【讨论】:

      【解决方案2】:

      看起来text.description 包含无法以文件系统的默认编码进行编码的字符。在默认文件系统编码为 cp1252 的 Windows 机器上可能会出现这种情况,但在其他平台上也可能出现这种情况,具体取决于它们的配置方式。

      您可以通过在打开文件时指定不同的编码来解决此问题 - utf-8 通常是一个不错的选择。

      with open('myfile.txt', 'w', encoding='utf-8') as f:
          f.write(text.description)
      

      请注意,如果您尝试从文件中读取,则需要指定编码:

      with open('myfile.txt', 'r', encoding='utf-8') as f:
          description = f.read()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-15
        • 2020-12-03
        • 1970-01-01
        • 1970-01-01
        • 2018-03-27
        • 2017-07-17
        相关资源
        最近更新 更多