-2

I have written a script on Linux which does some operations on a text file. The output is a clean text file as expected. The first lines are as below:


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 

How can I return the output text file as json in a way that each two following words in the text will be the key/value pair? The word that has no word afterwards should be assigned a value of null.

RobC
  • 22,977
  • 20
  • 73
  • 80
Reza
  • 113
  • 2
  • 11
  • 4
    could you please share the sample output you are expecting here? if you have started with a sample script, could you share that as well? – segFaulter Jan 14 '19 at 08:02
  • You should use jq and refer tho this link for more info https://stackoverflow.com/questions/38860529/create-json-using-jq-from-pipe-separated-keys-and-values-in-bash – Raghuram Jan 14 '19 at 08:39
  • @segFaulter i have no idea what to do. the script i have written gets a text and removes certain words from it. i put it here if you want. but i don't think it can be helpful. – Reza Jan 14 '19 at 10:09

1 Answers1

1

you can try using python to do this for you. below is the sample code in python 3.6 you can read a file into an array and use the below optimization to achieve your output.

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

Hope this helps! cheers!

segFaulter
  • 180
  • 9
  • the above code works perfectly well. but when i add more items to the list 'lines', it doesn't show anything in the output. why??? – Reza Jan 16 '19 at 08:11
  • it was very useful! can you please explain a bit about each line of code? – Reza Jan 17 '19 at 12:37