如何将文本文件中的后两个单词作为json返回?

时间:2019-01-14 07:58:45

标签: json bash text-files

我已经在Linux上编写了一个脚本,该脚本对文本文件进行了一些操作。输出是一个纯文本文件,如预期的那样。第一行如下:


Hamlet 

William Shakespeare 

Edited Barbara B Mowat Paul Werstine 

Michael Poston Rebecca Niles 

Folger Shakespeare Library 

httpwwwfolgerdigitaltextsorgchapter5playHam 

Created Jul 31 2015 FDT version 092 

Characters Play 

line 17 POLONIUS father Ophelia Laertes councillor King Claudiusthis line substituted  
GHOST 

如何以文本中的每个后两个单词为键/值对的方式将输出文本文件作为json返回?此后没有单词的单词应分配值为null

1 个答案:

答案 0 :(得分:1)

您可以尝试使用python为您执行此操作。以下是python 3.6中的示例代码,您可以将文件读取到数组中,并使用以下优化方法来实现输出。

import itertools

lines=["Hamlet"
,"William Shakespeare"
,"Edited Barbara B Mowat Paul Werstine "
,"Michael Poston Rebecca Niles"
,"Folger Shakespeare Library"
,"httpwwwfolgerdigitaltextsorgchapter5playHam"
,"Created Jul 31 2015 FDT version 092"
,"Characters Play"
,"line 17 POLONIUS father Ophelia Laertes councillor King Claudiusthis line substituted GHOST"]

LinesMap=dict()
for line in lines:
    list=[l for l in line.split(' ')]
    d = dict(itertools.zip_longest(*[iter(list)] * 2, fillvalue=None))
    LinesMap = {**LinesMap, **d}

print(LinesMap)

How to read/write a file in python

how to convert dictionary to json in python

希望这会有所帮助!欢呼!