我在 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
。
您可以尝试使用 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)
希望这可以帮助!干杯!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句