Let Python tell you jokes and stories, an interesting Python case

Time:2020-1-14

Preface

The text and pictures of the article are from the Internet, only for learning and communication, and do not have any commercial use. The copyright belongs to the original author. If you have any questions, please contact us in time for handling.

Author: tomato ha ha

PS: if you need Python learning materials, you can click the link below to get them by yourself

http://note.youdao.com/noteshare?id=3054cce4add8a909e784ad934f956cef

This preparation introduces Python crawler crawling web data, parsing and application in practice, and intends to write several articles, starting with the most basic Python crawler syntax, to introduce the crawler step by step, and finally realize a more complete example.

This series includes:

  • Introduction and application of request Library

  • Introduction and application of beautifulsoup Library

  • Regular expression matching and its application

  • Example of dialogue robot

  • Tkinter library making interface and python program are packed into executable EXE file

This article mainly gives a demonstration of exe application that I finally made, the main purpose is to improve the readers’ interest in learning.

Finally, the chat robot can crawl the information in the designated website according to the user’s input instructions, parse it in the background, and return the results to the interface.

I put this exe application at the end, which can be run directly on the computer. You can download it to play or send it to your friends to show it.

Run the screenshot as follows:

在这里插入图片描述

Users can input instructions, such as: “tell me a joke“, “tell me a joke”, “find me a good night on the Internet”, etc. As follows:

在这里插入图片描述

在这里插入图片描述

The development tool I use is Spyder. In the following articles, I will gradually explain the principle and implementation method of this example.

The code is attached below. Interested students can copy their own running and try it.

from tkinter import *
 import time
 import requests
 from bs4 import BeautifulSoup
 import bs4
 import random
 import re 
 def getHTMLText(url):
     try:
         r = requests.get(url, timeout=30)
         r.raise_for_status()
         #r.encoding = r.apparent_encoding
         return r.text
     except:
         print("faile")
         return ""
 ​
 def fillUnivList(ulist, html):
     soup = BeautifulSoup(html, "html.parser")
     for tr in soup.find_all('article'):
         if isinstance(tr, bs4.element.Tag):
             tds = tr('a')
             ulist.append([tds[0].string, tds[1].string, tds[2].string])
 def printUnivList(ulist,k):
     return ulist[k][0]
 ​
 def getduanzi():
     uinfo = []
     k=1
     u = 'http://duanziwang.com/category/%E4%B8%80%E5%8F%A5%E8%AF%9D%E6%AE%B5%E5%AD%90/'
     i=random.randint(1,49)
     url=u+str(i)+'/'
     html = getHTMLText(url)
     fillUnivList(uinfo, html)
     k=random.randint(0,9)
     return printUnivList(uinfo,k)
 def fill2(ulist,html):
     soup = BeautifulSoup(html, "html.parser")
     for tr in soup.find_all('div','article block untagged mb15 typs_hot'):
         if isinstance(tr, bs4.element.Tag):
             tds = tr.find('div','content')
             tdss=tds('span')         
             reg = re.compile(']*>')
             text=reg.sub('',str(tdss))
             regg = re.compile('\[|\]|\n')
             text=regg.sub('',text)
             ulist.append(text)
 def getjoke():
     ulist=[]
     u='https://www.qiushibaike.com/text/page/'
     i=random.randint(1,13)
     url=u+str(i)+'/'
     html=getHTMLText(url)
     fill2(ulist,html)
     k=random.randint(0,16)
     #print(str(ulist[k]))
     return str(ulist[k])
 def getHTMLText2(url):
     try:
         r = requests.get(url, timeout=30)
         r.raise_for_status()
         r.encoding = r.apparent_encoding
         return r.text
     except:
         return ""
 def geturl(url,text):
     html=getHTMLText2(url)
     soup = BeautifulSoup(html, "html.parser")
     for tds in soup.find_all('a'):
         #print(tds.string)
         if str(tds.string) in text:
             #print(tds.attrs['href'])
             return tds.attrs['href']
     return ''
 def getmoreurl(url):
     html=getHTMLText2(url)
     soup = BeautifulSoup(html, "html.parser")
     try:
         li=soup.find_all('li',attrs={'class':'articleTitle fl'})
         k=random.randint(0,len(li)-1)
         return li[k]('a')[0].attrs['href']
     except:
         return ''
 def getsen(url):
     html=getHTMLText2(url)
     soup = BeautifulSoup(html, "html.parser")
     try:
         li=soup.find('p')
         reg = re.compile('.*')      
         l=reg.findall(str(li))
         #print(l)
         k=random.randint(0,len(l)-1)
         text=re.findall('[\u4e00-\u9fa5]+',l[k])
         x=''
         if len(text):
             for t in text[:-2]:
                 x=x+t+','
             return x+text[-1]+'。'
         else:
             Return "I'm sorry. There is a small problem. Please try again! "
     except:
         Return "sorry, I didn't find what you wanted."
 def getsentance(text):
     start_url = 'http://www.siandian.com'
     urll='http://www.siandian.com/tags.html'
     end1=geturl(urll,text)
     if end1=='':
         Return "sorry, I didn't find what you wanted. "
     else:
         end2=getmoreurl(start_url+end1)
         if end2=='':
             Return "sorry, I didn't find what you wanted. "
         else:
             #print(start_url+end2)
             return getsen(start_url+end2)
 def xiaotang(s):
     sign=1;
     while(sign):
         If 'segment' in S:
             While ('segment 'in s or' continue 'in s or' come again 'in s or S = =' '):
                 return getduanzi()
         Elif 'joke' in S:
             While ('joke 'in s or' continue 'in s or' come again 'in s or S = =' '):
                 return getjoke()
         Elif 'sentence' in s or 'word' in S:
                 return getsentance(s)  
         Elif 'fool' in s or 'grass' in s or' Day 'in S:
             Return 'this is a dirty word. You can't say it.'
         Elif 'two' in s or 'rubbish' in s or 'fool' in S:
             Are you the devil? '
             x=''
             for i in range(10):
                 x=x+t+' !'+'\n'
             return x
         else:
             Return "I don't seem to understand \ n"
 def main():
   def start():
       Strmsg = 'small sugar:' + time.strftime ("% Y -% m -% d% H:% m:% s",
                                   time.localtime()) + '\n '
       txtget.insert(END, strMsg, 'redcolor')
       Txtget. Insert (end, 'Hello, what can I do for you? )
   Def sendmsg(): send message
     t=txtMsg.get('0.0', END)
     txtMsg.delete('0.0', END)
     Strmsg = 'I:' + time.strftime ("% Y -% m -% d% H:% m:% s",
                                   time.localtime()) + '\n '
     for i in range(int(txtget.index(END).split(".")[0])-int(txtMsgList.index(END).split(".")[0])+1):
         txtMsgList.insert(END, '\n')
     txtMsgList.insert(END, strMsg, 'greencolor')
     txtMsgList.insert(END, t)
     txtMsgList.see(END)
     for i in range(int(txtMsgList.index(END).split(".")[0])-int(txtget.index(END).split(".")[0])+1):
         txtget.insert(END, '\n')
         txtget.see(END)
 ​
 ​
 ​
     Strmsg = 'small sugar:' + time.strftime ("% Y -% m -% d% H:% m:% s",
                                   time.localtime()) + '\n '
     for i in range(int(txtMsgList.index(END).split(".")[0])-int(txtget.index(END).split(".")[0])+1):
         txtget.insert(END, '\n')
     txtget.insert(END, strMsg, 'redcolor')
     txtget.insert(END, xiaotang(t))
     txtget.see(END)
     for i in range(int(txtget.index(END).split(".")[0])-int(txtMsgList.index(END).split(".")[0])+1):
         txtMsgList.insert(END, '\n')
         txtMsgList.see(END)
 ​
 ​
   Def cancelmsg(): cancel message
     txtMsg.delete('0.0', END)
 ​
   Def sendmsgevent (event): send message event
       sendMsg()
 ​
   #Create window 
   t = Tk()
   t. Title ('small sugar assistant ')
 ​
   #Create frame container
   frmLT = Frame(width=500, height=320, bg='#F19C8B')
   frmLC = Frame(width=500, height=150, bg='#F19C8B')
   frmLB = Frame(width=500, height=30,bg='white')
   frmRT = Frame(width=200, height=500,bg='#F19C8B')
 ​
   #Create control
   txtMsgList = Text(frmLT,width=40,bd=0)
   Txtmsglist. Tag ﹐ config ('greencolor ', ground =' ﹐ 008c00 ') ﹐ create tag
   txtMsg = Text(frmLC)
   txtget = Text(frmLT,width=40,bd=0)
   Txtget. Tag ﹐ config ('redcolor ', foreground =' ﹐ dc143c ') ﹐ create tag
   start()
   #txtMsg.bind("", sendMsgEvent)
   txtMsg.bind('',sendMsgEvent)
   Btnsend = button (frmlb, text = 'send', width = 8, command = sendmsg, BG = '', BD = 0)
   Btncancel = button (frmlb, text = 'Cancel', width = 8, command = cancelmsg, BG = '(f3ada0', BD = 0)
   scollor=Scrollbar(bg='white')
   scollor.config(command=txtget.yview)
   scollor.config(command=txtMsgList.yview)
   txtget.config(yscrollcommand=scollor.set)
   txtMsgList.config(yscrollcommand=scollor.set)
   imgInfo = PhotoImage(file = "aa.png")
   lblImage = Label(frmRT, image = imgInfo)
   lblImage.image = imgInfo
 ​
   #Window layout
   frmLT.grid(row=0, column=0, columnspan=2, padx=0, pady=0)
   frmLC.grid(row=1, column=0, columnspan=2, padx=0, pady=0)
   frmLB.grid(row=2, column=0, columnspan=2,padx=0)
   scollor.grid(row=0,column=2,sticky=N+S)
   frmRT.grid(row=0, column=3, rowspan=3, padx=0, pady=0)
   #Fixed size
   frmLT.grid_propagate(0)
   frmLC.grid_propagate(0)
   frmLB.grid_propagate(0)
   frmRT.grid_propagate(0)
 ​
   btnSend.grid(row=2, column=0)
   btnCancel.grid(row=2, column=1)
   lblImage.grid()
   txtget.grid(row=0,column=0)
 ​
   txtMsgList.grid(row=0,column=1)
 ​
   txtMsg.grid()
 ​
   #Main event cycle
   t.mainloop()
 ​
 if __name__ == '__main__':
     main()