闲来无事用Python写了一个成语练字的小工具,输入框输入一行汉字,然后可以生成多个成语连成这行文字,和生成藏头诗有些类似。
知识点就是爬虫的使用,本例中用requests实现爬虫,用bs4这个lib实现URL解析,pyqt实现UI
代码如下:
1 from PyQt5 import QtCore, QtGui, QtWidgets 2 3 from PyQt5.QtWidgets import (QWidget, QPushButton, 4 QFrame, QApplication) 5 import sys 6 import requests, urllib 7 from bs4 import BeautifulSoup 8 import random 9 10 URL = 'http://chengyu.t086.com/' 11 12 HOST = { 13 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 14 'Referer': 'http://chengyu.t086.com/' 15 } 16 17 class MainWindow(QtWidgets.QWidget): 18 19 def __init__(self): 20 super().__init__() 21 22 self.gridLayout = QtWidgets.QGridLayout() 23 24 self.wordEdit = QtWidgets.QLineEdit() 25 self.genBtn = QtWidgets.QPushButton("生成") 26 self.textBox = QtWidgets.QTextEdit() 27 28 self.gridLayout.addWidget(self.wordEdit, 1, 1) 29 self.gridLayout.addWidget(self.genBtn, 1, 2) 30 self.gridLayout.addWidget(self.textBox, 2, 1) 31 32 self.genBtn.clicked[bool].connect(self.genTextBox) 33 34 self.setLayout(self.gridLayout) 35 self.setWindowTitle("成语生成器") 36 37 def genTextBox(self): 38 self.textBox.clear() 39 input_word = self.wordEdit.text() 40 for letter in input_word: 41 if u'\u4e00' <= letter <= u'\u9fa5': #判断是否为汉字 42 self.textBox.append(ConvertToChengyu(letter)) 43 44 45 def ConvertToChengyu(letter): 46 chengyuList = [] 47 u = urllib.parse.quote(letter, encoding='gb2312') 48 url = 'http://chengyu.t086.com/chaxun.php?q1={}&q2=&q3=&q4='.format(u) 49 start_html = requests.get(url, headers=HOST) 50 start_html.encoding = 'gb2312' 51 soup = BeautifulSoup(start_html.text, "html.parser") 52 listw = soup.find_all('td', class_='td1') 53 for w in listw: 54 chengyuList.append(w.text) 55 chengyuList = list(filter(lambda n: len(n) == 4, chengyuList)) 56 print(chengyuList) 57 if len(chengyuList): 58 i = random.randint(0, len(chengyuList) - 1) 59 return chengyuList[i] 60 else: 61 return "No Result" 62 63 64 if __name__ == '__main__': 65 app = QApplication(sys.argv) 66 w = MainWindow() 67 w.show() 68 sys.exit(app.exec_())
运行效果如下: