【问题标题】:How to save Python API request to .txt file如何将 Python API 请求保存到 .txt 文件
【发布时间】:2019-10-09 11:59:21
【问题描述】:

我正在使用 Google Docs Python API,特别是官方示例Extract text from a document 一切运行良好,最后我将提取的文本打印到终端,这是最后一段代码 main func 的结果

def main():
    """Uses the Docs API to print out the text of a document."""
    credentials = get_credentials()
    http = credentials.authorize(Http())
    docs_service = discovery.build(
        'docs', 'v1', http=http, discoveryServiceUrl=DISCOVERY_DOC)
    doc = docs_service.documents().get(documentId=DOCUMENT_ID).execute()
    doc_content = doc.get('body').get('content')
print(read_strucutural_elements(doc_content))

问题是我在尝试将该文本保存到 .txt 文件时遇到问题,收到此错误消息

f.write(read_strucutural_elements(doc_content)) UnicodeEncodeError: 'ascii' 编解码器无法在位置 64 对字符 u'\xfa' 进行编码:序数 不在范围内(128)

read_structural_elements 调用的返回类型是

print(type(read_strucutural_elements(doc_content)))

<type 'unicode'>

有什么建议吗?

干杯!

【问题讨论】:

    标签: python google-docs-api


    【解决方案1】:

    如果您从终端运行脚本,您所要做的就是使用 > 运算符将输出写入文件。像这样的:

    python script.py > outfile.txt
    

    这将获取终端中正在打印的任何输出并将其转储到指定的文件中。

    【讨论】:

    • 也可以,已经试过了。感谢“print(read_strucutural_elements(doc_content)) UnicodeEncodeError: 'ascii' codec can't encode character u'\xfa' in position 64: ordinal not in range(128)”
    【解决方案2】:

    这也很有效

    def main():
        """Uses the Docs API to print out the text of a document."""
        credentials = get_credentials()
        http = credentials.authorize(Http())
        docs_service = discovery.build(
            'docs', 'v1', http=http, discoveryServiceUrl=DISCOVERY_DOC)
        doc = docs_service.documents().get(documentId=DOCUMENT_ID).execute()
        doc_content = doc.get('body').get('content')
        text = read_strucutural_elements(doc_content)
        print(text.encode('utf-8'), file=open("output.txt", "a"))
    

    只需将 read_structural_elements(doc_contet) 分配给一个新的变量 text,然后 print(如果需要)对其应用 .encode('utf-8') 方法。最后将文件参数包装到 print 语句中,以将“文本”内容保存到名为 output.txt 的文件中

    希望它也可以帮助其他人。

    干杯!

    【讨论】:

      猜你喜欢
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      相关资源
      最近更新 更多