如何将 Python API 请求保存到 .txt 文件

How to save Python API request to .txt file

我用的是Google文档PythonAPI,具体是官方的例子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' codec can't encode character u'\xfa' in position 64: ordinal not in range(128)

read_structural_elements调用的return类型是

print(type(read_strucutural_elements(doc_content)))

<type 'unicode'>

有什么建议吗?

干杯!

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

python script.py > outfile.txt

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

这也有效

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) 分配给新的变量文本,然后打印(如果需要)应用 .encode('utf-8') 方法。最后将文件参数包装到 print 语句以将“文本”内容保存到名为 output.txt

的文件中

希望对其他人也有帮助。

干杯!