how to get a A SUGGESTION, not just a word in python

Question:

i have a list of suggestion parsed from json which look likes ['just a suggestion', 'and this too suggestion', 'dont care, this suggestion']

and i write this code:

import json
import random
import dpath.util as dp

with open('.logs') as json_file:
    data = json.load(json_file)
    res = dp.values(data, "/posts/*/com")
    file = open(".text", "w")
    file.write(str(res))
    file.close()
    file = open(".text", "r")
    tt = file.read()
    text = random.choice(tt.split())
    print(text)

but, this give to me only words. something like care or another word from list. how do i get a random suggestion from a list?

Asked By: Yui

||

Answers:

IIUC you have a string read from a file that you want to treat like a
list so you need:

import ast
(...)
l = ast.literal_eval(tt)
text = random.choice(l)
print(text)
Answered By: Arkadiusz Drabczyk

If I understand you correctly, you don’t need this temporary file, and you could just do:

import json
import random
import dpath.util as dp

with open('.logs') as json_file:
    data = json.load(json_file)
    res = dp.values(data, "/posts/*/com")
    text = random.choice(res)
    print(text)
Answered By: Jasmijn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.