Visualizzazione post con etichetta json. Mostra tutti i post
Visualizzazione post con etichetta json. Mostra tutti i post

giovedì 8 aprile 2021

PYTHON - Light database from json file

 A very light textual database, very simple and basic. 

Download the two files maker.py and lightdb.py in the same directory. Run lightdb.py to build the database on a json file. Then there is the possibility to add data directly from lightdb or you can build a .py file that will serve to manage the database. There is also the possibility to transform the json file into an excel file.

 You can download  the file from repo on github: lightdb

sabato 3 aprile 2021

PYTHON - Make and read JSON file with JSON library

Simple example for to show python power
import json
import sys
#Write and read json file with json library and dict
def makeJSON(jsFile):
    dict={}
    while True:
        chiave=input("Chiave> ")
        if chiave=='#e':
            break
        valori=input("Valori> ")
        lista=valori.split(' ')
        dict[chiave]=lista
    with open(jsFile,"w") as json_file:
        json.dump(dict, json_file)

def readJSON(jsFile):
    dict={}
    with open(jsFile,"r") as json_file:
        dict=json.load(json_file)
    return dict

def understandvalues(dict):
    n=0
    f=0.0
    l=[]
    d={}
    klist=list(dict.keys())
    for i in range(len(klist)):
        val=dict[klist[i]]
        if type(val)==type(l):
            print("Lista")
        elif type(val)==type(n) or type(val)==type(f):
            print("numero")
        elif type(val)==type(d):
            print("dizionario")

if __name__ == "__main__":
    comandi="Ho to use: ej3.py (r or w) (file name) \nr read json file\nw write json file"
    try:
        if sys.argv[1]=='r':
            d=readJSON(sys.argv[2])
            understandvalues(d)
            print(d)
        elif sys.argv[1]=='w':
            makeJSON(sys.argv[2])
        else:
            print(comandi)
    except:
        print(comandi)

PYTHON - Building a memory based on external stimuli

This script parses the incoming phrase with the keys contained in the json file, if it finds the key it processes a response, otherwise it adds the key and rewrites the json file.
import json
#Da stimoli esterni il software allarga le proprie conoscenze

def caricaCoscienza(nomeCoscienza):
    with open(nomeCoscienza,"r") as json_file:
        dictFromJSon=json.load(json_file)
    return dictFromJSon

def memorizza(valori,dict,nomeCoscienza):
    chiave=valori[0]
    lista=[]
    for i in range(len(valori)):
        if i>0:
            lista.append(valori[i])
    dict[chiave]=lista
    with open(nomeCoscienza,"w") as json_file:
            json.dump(dict, json_file)
    with open(nomeCoscienza,"r") as json_file:
        dictFromJSon=json.load(json_file)
    return dictFromJSon

def elabora(valori,ch,keys,dict):
    chiave=keys[ch]
    risposta=dict[chiave]
    return risposta

def ricerca(ingresso,dict,nomeCoscienza):
    keys=list(dict.keys())
    valori=ingresso.split(' ')
    trovato=False
    r=''
    for i in range(len(keys)):
        for c in range(len(valori)):
            if keys[i]==valori[c]:
                trovato=True
                ch=i
    if not(trovato):
        dict=memorizza(valori,dict,nomeCoscienza)
    else:
        r=elabora(valori,ch,keys,dict)
    return r


if __name__ == "__main__":
    dict=caricaCoscienza("result.json")
    dato=input(">")
    print(ricerca(dato,dict,"result.json"))

PYTHON - FROM DICTIONARIES to JSON

Python dictionaries: a power; python dictionaries + JSON: super power.
import json
#HOW TO MANAGE DICTIONARY
#+-+-+-+-+-+-+-+-+-+-+-+#
d = {
  "Chiave": "Codice",
  "Costo": 1.23,
  "Ricarico": 30,
  "Listino": 3.00
}
c = d.items()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
c = d.keys()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
c=d.values()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
nd = {
    "dizionario":{"subDict":["ch1","ch2","ch3"],
                "other":"otherSub"
                },
    "numero":2,
    "codice":"codice"
}
c=nd.items()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
c = nd.keys()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
c=nd.values()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
newD=lista[0]
c=newD.values()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
nuovaLista=lista[0]
for i in range(len(nuovaLista)):
    print(nuovaLista[i])
print("Costruzione JSON")
with open("result.json", "w") as json_file:
    json.dump(nd, json_file)
json_string = json.dumps(nd)
print(json_string)
with open("result.json","r") as json_file:
    dictFromJSon=json.load(json_file)
print(dictFromJSon)

giovedì 1 aprile 2021

PYTHON - JSON MAKER

Maker JSON Files
Writing a json file can be boring, with this very simple script it's boring all the same, but at least in the end everything is correct.
########################################
# json files editor to use as database #
########################################

import sys,os
import curses
import json

def interpreta(o,file,next,cont):
    if next=='#k' and cont==0:
        file=file+'\"'+o+'\":'
        next=''
        cont+=1
    elif next=='#k' and cont>0:
        file=file+',\"'+o+'\":'
        next=''
    elif next=='#v':
        file=file+'\"'+o+'\"'
        next=''
    elif next=='#vl':
        c=o.split(',')
        file=file+'['
        for i in range(len(c)):
            file=file+'\"'+c[i]+'\"'
            if i!=len(c)-1:
                file=file+','
        file=file+']'
        next=''
    if o=='#k' and cont==0:
        file='{'
        next='#k'
    if o=='#k' and cont>0:
        next='#k'
    if o=='#v':
        next='#v'
    elif o=='#vl':
        next='#vl'
    elif o=='#vd':
        next='#vd'
    return file,next,cont

def main():
    print("JSON maker")
    print("commands: #k new key - #v new value - #vl new list value - #e save and exit")
    file=''
    cont=0
    next=''
    nomeFile=''
    while True:
        o=input(">")
        if o=='#e':
            file=file+"}"
            nomeFile=input("Nome del file >")
            f=open(nomeFile,"w")
            f.write(file)
            f.close()
            sys.exit()
        file,next,cont=interpreta(o,file,next,cont)


if __name__ == "__main__":
    main()

domenica 28 marzo 2021

PYTHON - MAKE A JSON FILE FROM DICT

Practical example of how to transform a dictionary into a json file.
The filename is updated using a variable contained in "count.py". Each file is added to the "listalogiche.dat" file.
From here we start for artificial intelligence.
import json
import conteggio
import sys

lista2={}
while True:
v1=input('Parola ')
if v1=='fine':
break
elif v1=='annulla':
sys.exit()
else:
v2=input('comando ')
lista2[v1]=v2
nomefile="comandi"+str(conteggio.conta)+".json"
#save lista2 as .json file
with open(nomefile, "w") as json_file:
json.dump(lista2, json_file)
#aggiornamento dei file di configurazione
f=open("conteggio.py","w")
n=conteggio.conta
n+=1
f.write('conta='+str(n))
f.close()
f=open("listalogiche.dat","a")
f.write(nomefile)
f.close()

venerdì 1 maggio 2020

PYTHON - INTERROGATE THE WEB WITH APIs

With python's REQUEST and JSON module it's simple. Below is an example of a query to the GNEWS.IO API
This very simple script allows you to search for articles related to the keywords you enter, using the GNEWS.IO API

import requests
import json
#http://gnews.io
api_token=''#here your gnews api

keywords=input('Parole chiave:')
indirizzo='https://gnews.io/api/v3/search?q='+keywords+'&token='+api_token
print(indirizzo)
r=requests.get(indirizzo)
file=r.text
output=json.loads(file)
for i in range(len(output['articles'])):
    print('Articoli: '+output['articles'][i]['title'])
    print('Descrizione: '+output['articles'][i]['description'])
    print('URL: '+output['articles'][i]['url'])
    print('Pubblicato il: '+output['articles'][i]['publishedAt'])

The web is full of APIs that can be used to collect any type of data.
If you like the blog remember to support my work through gofundme or by sending cryptocurrencies. Thanks