【问题标题】:Saving print output as dict or JSON将打印输出保存为 dict 或 JSON
【发布时间】:2019-10-06 09:21:55
【问题描述】:

我有以下将 boto3 用于 AWS 的代码。

import boto3
from trp import Document

# Document
s3BucketName = "bucket"
documentName = "doc.png"

# Amazon Textract client
textract = boto3.client('textract')

# Call Amazon Textract
response = textract.analyze_document(
    Document={
        'S3Object': {
            'Bucket': s3BucketName,
            'Name': documentName
        }
    },
    FeatureTypes=["FORMS"])

#print(response)

doc = Document(response)

for page in doc.pages:
    # Print fields
    print("Fields:")
    for field in page.form.fields:
        print("Key: {}, Value: {}".format(field.key, field.value))

我正在尝试将该函数的输出保存为 dict、JSON 或 CSV,但我还不是经验丰富的 Python 程序员。

我试过了:

key_map = {}
filepath = 'output.txt'
with open(filepath) as fp:
    line = fp.readline()
    cnt = 1
    while line:
        for page in doc.pages:
            # Print fields
            print("Fields:")
            for field in page.form.fields:
                #print("Key: {}, Value: {}".format(field.key, field.value))
                key_map[str(field.key, field.value)] = cnt
                line = fp.readline()
                cnt +=1

但我认为这个解决方案不起作用。关于如何将 for 循环的输出保存为 JSON 的任何提示?

【问题讨论】:

  • 您尝试的内容似乎是从文件中读取而不是写入。所以你想要的只是将doc = Document(response) 的输出写入文件?
  • 是的。因此,将打印输出 (print("Key: {}, Value: {}".format(field.key, field.value)) 保存为 JSON 或 CSV。

标签: python json dictionary amazon-textract


【解决方案1】:

如果你想作为 csv 输出,你可以使用 csv 模块 作为:

import csv

doc = Document(response)

with open('aws_doc.csv', mode='w') as aws_field_file:
    field_write = csv.writer(aws_field_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    for page in doc.pages:
        for field in page.form.fields:
            # This will write it as your <key>, <value>
            field_write.writerow([field.key, field.value])

如果您想要文件中的标题,您还可以使用DictWriter,这样您就可以轻松地传递字典: https://docs.python.org/3.4/library/csv.html#csv.DictWriter

【讨论】:

  • 成功了!谢谢!我会查看标题。
猜你喜欢
  • 2011-12-19
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 2022-07-04
  • 1970-01-01
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多