删除所有非字母字符,保留字符串中的空格

时间:2019-11-22 16:32:18

标签: python python-3.x

我不是程序员。我是一位正在学习Python并正在制作艺术作品的艺术家。我已经在YouTube和Stackoverflow上做到了这一点。

说...

我从API获取文本,然后将其显示在标签中。原始文本如下所示:

{"word":"hello","synonyms":["hi","how-do-you-do","howdy","hullo"]},单词随用户输入而变化。

我只想在方括号内显示单词,不带标点。经过大量Stackoverflow之后,我发现re.sub(r"\W", "", text, flags=re.I)(亲爱的上帝,我不知道这意味着什么,只是w,W表示字母/非)。这给了我

"wordhellosynonymshihowdoyoudohowdyhullo

叹气。如何保存我的空间?我想我可以自己删除前17个单词。

完整代码(不好意思)。我知道它的一部分坏了,我一次要扑灭一堆火。最终项目是一个程序,该程序返回用户输入的单词的同义词,然后询问用户输出是否正确。结果最终将显示在图形中。有时故意输出错误,我不需要修复此问题。

'''

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() ```

3 个答案:

答案 0 :(得分:4)

您得到的是一个JSON字符串。您需要解析JSON。有一个图书馆。

import json
text = '{"word":"hello","synonyms":["hi","how-do-you-do","howdy","hullo"]}'
data = json.loads(text)
print(" ".join(data["synonyms"]))

答案 1 :(得分:3)

您可以使用Json序列化来完成这项工作。通过API,您将获得JSON格式的响应。

import json 

response = <your response>
json_obj = json.loads(response)
strvalue = " ".join(json_obj["synonyms"])
print(strvalue)

Json示例:https://docs.python.org/3/library/json.html

答案 2 :(得分:1)

获得的对象称为JSONdict,它很棒。

如果将其分配给这样的变量:

a = {"word":"hello","synonyms":["hi","how-do-you-do","howdy","hullo"]}

然后您可以像这样引用它们:

for item in a['synonyms']:
     print(item)

为了让SO帮助您提供要实现的目标的完整工作示例,这将非常有用