Reputation: 53
I'm not a programmer. I'm an artist learning Python for an art installation I'm making. I've made it this far on Youtube and Stackoverflow.
That said...
I'm getting text from an API, which I then display in a label. The raw text looks like this:
{"word":"hello","synonyms":["hi","how-do-you-do","howdy","hullo"]}
, The words change depending on user-input.
I want to only display the words within the brackets, without punctuation. After much Stackoverflow, I discover re.sub(r"\W", "", text, flags=re.I)
(dear God, I don't know what it means, just that w,W means alphabetic/Non). Which gives me:
"wordhellosynonymshihowdoyoudohowdyhullo
sigh. How do I preserve my spaces? I think I can strip the first 17 words on my own.
Full code (I'm embarrassed). I know parts of it are broken, I'm putting out one fire at a time. The final project is a program that returns synonyms of user-entered words and then asks the user if the ouput is correct. The result will eventually be display in a graph. The output is intentionally wrong sometimes, I don't need this fixed.
'''
import requests
from tkinter import *
import tkinter.messagebox
from tkinter import font
import re
import string
root = Tk ()
Graph = Tk ()
def create_grid(event=None):
w = c.winfo_width() # Get current width of canvas
h = c.winfo_height() # Get current height of canvas
c.delete('grid_line') # Will only remove the grid_line
# Creates all vertical lines at intevals of 100
for i in range(0, w, 100):
c.create_line([(i, 0), (i, h)], tag='grid_line')
# Creates all horizontal lines at intevals of 100
for i in range(0, h, 100):
c.create_line([(0, i), (w, i)], tag='grid_line')
c = Canvas(Graph, height=1600, width=1600, bg='white')
c.pack(fill=BOTH, expand=True)
c.bind('<Configure>', create_grid)
#lets you press enter for query instead of clicking w mouse
#the "forget" objects deletes the button and the widget.
# Should figure out either a timeout, restart, or back-button.
def onReturn(*args):
command = Buttonclick()
Button.pack_forget(Button_1)
Entry_1.pack_forget()
tkinter.messagebox.showinfo("Help!","This installation measures the accuracy of synoymns delivered. In the next window, please select 'yes' if your synonym was correct, and 'no' if it was not.")
answer = tkinter.messagebox.askquestion("Accurate?", "Synonym Accurate?")
## Immeidately above and below is the messagebox text. Will eventually connect to a grid.
if answer == "yes":
print("thanks!")
if answer == "no":
print("FUCK. Sorry.")
### Add yes/no actions for message box!
#Gets the user entry when button is pressed, either by mouse or enter key.
def Buttonclick():
Entry_1.get()
# this is the API that gets the synonyms - the url must be www.URLURLURL.URL.com/words/ENTRY HERE!!/typeof
#DO NOT FUCKING TOUCH THIS. IT'S MAGIC AND I DO NOT CONTROL IT.
url = "https://wordsapiv1.p.rapidapi.com/words/"+Entry_1.get()+"/synonyms"
headers = {
'x-rapidapi-host': "wordsapiv1.p.rapidapi.com",
'x-rapidapi-key': "myapikey"
}
punct = "!#$%&'()*+,-./:;?@[\]^_`{|}~"
response = requests.request("GET", url, headers=headers,)
newstring = response
text = response.text
print(response.text)
label = Label(root, text= re.sub(r"\W", "", text, flags=re.I), font="helv 18", bg="black", fg="white", )
label.pack()
testing = Button(root, text="Press Spacebar to Restart", font="Helv 24", bg="red", fg="white",command=Spacebar)
testing.bind("<space>",Spacebar)
testing.pack()
def Spacebar():
root.configure(background='blue')
root.geometry("1600x1600+50+50")
Entry_1 = Entry(root, bg="black", fg="White", font="Helv 48")
Entry_1.bind("<space>", onReturn)
Entry_1.pack(expand=1)
Button_1 = Button(root, text="Type Word, Press Enter For Synonym", font="Helv 24", bg="blue", fg="white", command=Buttonclick)
Button_1.pack(fill=X, expand=1)
Label.forget()
#Initial button and text entry box, sized correctly.
root.configure(background='blue')
root.geometry("1600x1600+50+50")
Entry_1 = Entry(root, bg="black", fg="White", font="Helv 48")
Entry_1.bind("<Return>", onReturn)
Entry_1.pack(expand=1)
Button_1 = Button(root, text="Type Word, Press Enter For Synonym", font="Helv 24", bg="blue", fg ="white", command=Buttonclick)
Button_1.pack(fill=X, expand=1)
root.mainloop() ```
Upvotes: 3
Views: 182
Reputation: 2884
The object you got is called a JSON or a dict
and it's awesome.
if you assign it to a variable like this:
a = {"word":"hello","synonyms":["hi","how-do-you-do","howdy","hullo"]}
you can then reference them like this:
for item in a['synonyms']:
print(item)
It would be really useful in order for SO to help you to provide what's called a full working example of what you're trying to achieve
Upvotes: 1
Reputation: 2576
What you got is a JSON string. You need to parse the JSON. There is a library for that.
import json
text = '{"word":"hello","synonyms":["hi","how-do-you-do","howdy","hullo"]}'
data = json.loads(text)
print(" ".join(data["synonyms"]))
Upvotes: 4
Reputation: 8154
You can use Json serialization for this work. From API you are getting response in JSON
format.
import json
response = <your response>
json_obj = json.loads(response)
strvalue = " ".join(json_obj["synonyms"])
print(strvalue)
Json example : https://docs.python.org/3/library/json.html
Upvotes: 3