【问题标题】:Word file to json in python在python中将Word文件转换为json
【发布时间】:2018-04-02 19:03:04
【问题描述】:

我有一些包含以下格式数据的 word(doc 和 docx)文件,我需要将它们转换为 JSON:

1.Name: ABC, Place: Maryland, Country: US, PHONE NO.:1234567890

2.Name: ABC, Place: Maryland, Country: US, PHONE NO.:1234567890

3.Name: ABC, Place: Maryland, Country: US, PHONE NO.:1234567890

在 python 中最简单的方法是什么?

【问题讨论】:

  • 你看过这个吗? python-docx.readthedocs.io/en/latest
  • 是的,但没有提到 doc 到 JSON 的转换。
  • 看来您可以解析 docx 的不同部分,然后使用 Json 模块构建您的自定义格式。没有准备好使用,遗憾的是

标签: python json python-3.x


【解决方案1】:

有一个 docx module(尽管它明确不支持旧式 .doc 文件),您可以将其与 csv 阅读器结合使用以拆分列,然后从第一列中获取行索引。

from docx import Document
import json

document = Document('existing-document-file.docx')
lines = [para.text for para in document.paragraphs]
lines = [line.partition('.') for line in lines]
lines = [(int(row_num), row_text) for row_num, _, row_text in lines]
lines = [(n, [txt.partition(':') for txt in row_text.split(',')]) for n, row_text in lines]
lines = {n: {key.strip(): val.strip() for key, _, val in row} for n, row in lines}
json_result = json.dumps(lines)

通过您的示例输入,我使用此代码得到以下输出:

'{"1": {"Name": "ABC", "Place": "Maryland", "Country": "US", "PHONE NO.": "1234567890"},
"2": {"Name": "ABC", "Place": "Maryland", "Country": "US", "PHONE NO.": "1234567890"},
"3": {"Name": "ABC", "Place": "Maryland", "Country": "US", "PHONE NO.": "1234567890"}}'

【讨论】:

    【解决方案2】:

    要使用的库:

    • 对于 docxtext 的转换使用 docx2text
    • 对于json转换使用json
    • 要在字典中存储值,请使用defaultdict() from collections

    步骤

    1. 使用docx2text将文档转换为字符串
    2. 将字符串转换为字符串列表,用新行\ncharacter 分割并删除垃圾空格''
    3. 对于列表中的每个元素,由: , 拆分以进行操作。 通过:2删除数字拼接
    4. 将列表li中的每个项目的每个键、值对存储在字典中
    5. 将dict对象添加到json_li
    6. 调用json.dumps(json_li)创建json字符串

    代码

    import docx2txt, json, collections
    # step 1 get docx text
    text = docx2txt.process("F:\workspace\StackOverFlow\guac.docx")
    # convert to list
    li = [x for x in text.split('\n')]
    # remove ''s i.e Nones
    li = list(filter(None, li))
    print(li)
    # json list
    json_li = []
    # convert and store all values
    for x in li:
        x = x[2:] # remove 1. 2. 3. ...
        y = x.split(',')
        print(y)
        d = collections.defaultdict()
        for m in y:
            z = m.split(':')
            z1 = [x.strip() for x in z]
            d[z1[0]] = z1[1]
        json_li.append(d)
    # JSON conversion
    print(json.dumps(json_li, indent=4))
    

    输出

    ['1.Name: ABC, Place: Maryland, Country: US, PHONE NO.:1234567890', '2.Name: ABC, Place: Maryland, Country: US, PHONE NO.:1234567890', '3.Name: ABC, Place: Maryland, Country: US, PHONE NO.:1234567890']
    ['Name: ABC', ' Place: Maryland', ' Country: US', ' PHONE NO.:1234567890']
    ['Name: ABC', ' Place: Maryland', ' Country: US', ' PHONE NO.:1234567890']
    ['Name: ABC', ' Place: Maryland', ' Country: US', ' PHONE NO.:1234567890']
    [
        {
            "Name": "ABC",
            "Place": "Maryland",
            "Country": "US",
            "PHONE NO.": "1234567890"
        },
        {
            "Name": "ABC",
            "Place": "Maryland",
            "Country": "US",
            "PHONE NO.": "1234567890"
        },
        {
            "Name": "ABC",
            "Place": "Maryland",
            "Country": "US",
            "PHONE NO.": "1234567890"
        }
    ]
    

    更新文档文件

    如果您有 doc 文件,请使用

    import textract
    text = textract.process("path_to_file")
    

    【讨论】:

      【解决方案3】:

      没有库/内置插件可以做到这一点。最简单的方法是将文件转换为 CSV(您自己删除所有逗号,然后用逗号替换空格,或者尽可能使用程序)

      然后您可以使用 csv 包中的 DictReader 类将文件转换为字典,然后使用 json 模块将其转储为 json 字符串。

      伪代码,例如转换为 csv 后。

      import json
      
      from csv import DictReader
      
      COLUMN_NAMES = ['your', 'column', 'names,', '...'] 
          #Or the first row will be the column
          #(and the resulting key in the dictionary ) names
      
      jsonCollection = {}
      with open("your_csv_file.csv") as csvFile:
          #fieldnames is optional here
          reader = DictReader(csvFile, fieldnames=COLUMN_NAMES)
          for row in reader:
              for colName, rowVal in row.items():
                  jsonCollection.setdefault(colName, []).append(rowVal)
      
      json.dumps(jsonCollection) #should get you what you want
      

      【讨论】:

      • 为什么是 CSV ? OP 说数据在 doc 和 docx 中
      • OP 也以最简单的方式要求它;将 csv 转换为字典(然后转换为 json)是 python 中的内置功能,而 doc/docx 并不是那么简单。
      • 人们在没有评论的情况下投反对票...你有什么建议? /耸肩
      猜你喜欢
      • 1970-01-01
      • 2015-01-13
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      • 2020-06-12
      • 2013-08-24
      • 2016-02-27
      相关资源
      最近更新 更多