這幾天在學習python的爬蟲, 無心中看到一篇博文 Python爬蟲之自制英漢字典 發現裏面的ctypes 和pyinstaller 還不瞭解,這邊文章說白了就是你輸入英文, python讀取你的輸入 而後發送一個http請求到有道翻譯,而後把翻譯的結果打印出來,這裏使用了ctypes來設置打印窗口的顏色,使用pyinstaller來打包python程序, 網上關於pyinstaller和ctypes介紹已經不少了html
Python打包方法——Pyinstallerpython
Python使用pyinstaller打包幾個小技巧 app
python ctypes 探究 ---- python 與 c 的交互 dom
代碼以下:學習
import requests from bs4 import BeautifulSoup import random import ctypes STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 FOREGROUND_DARKBLUE = 0x01 # 暗藍色 FOREGROUND_DARKGREEN = 0x02 # 暗綠色 FOREGROUND_DARKSKYBLUE = 0x03 # 暗天藍色 FOREGROUND_DARKRED = 0x04 # 暗紅色 FOREGROUND_DARKPINK = 0x05 # 暗粉紅色 FOREGROUND_DARKYELLOW = 0x06 # 暗黃色 FOREGROUND_DARKWHITE = 0x07 # 暗白色 FOREGROUND_DARKGRAY = 0x08 # 暗灰色 FOREGROUND_BLUE = 0x09 # 藍色 FOREGROUND_GREEN = 0x0a # 綠色 FOREGROUND_SKYBLUE = 0x0b # 天藍色 FOREGROUND_RED = 0x0c # 紅色 FOREGROUND_PINK = 0x0d # 粉紅色 FOREGROUND_YELLOW = 0x0e # 黃色 FOREGROUND_WHITE = 0x0f # 白色 std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) # 設置文字顏色 def set_cmd_text_color(color, handle=std_out_handle): return ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color) # 重置文字顏色爲白色 def reset_color(): set_cmd_text_color(FOREGROUND_DARKWHITE) # 以指定顏色輸出文字 def cprint(mess, color): color_dict = {'暗藍色': FOREGROUND_DARKBLUE, '暗綠色': FOREGROUND_DARKGREEN, '暗天藍色': FOREGROUND_DARKSKYBLUE, '暗紅色': FOREGROUND_DARKRED, '暗粉紅色': FOREGROUND_DARKPINK, '暗黃色': FOREGROUND_DARKYELLOW, '暗白色': FOREGROUND_DARKWHITE, '暗灰色': FOREGROUND_DARKGRAY, '藍色': FOREGROUND_BLUE, '綠色': FOREGROUND_GREEN, '天藍色': FOREGROUND_SKYBLUE, '紅色': FOREGROUND_RED, '粉紅色': FOREGROUND_PINK, '黃色': FOREGROUND_YELLOW, '白色': FOREGROUND_WHITE } set_cmd_text_color(color_dict[color]) print(mess) reset_color() # 顏色列表 color_list = ['暗藍色','暗綠色','暗天藍色','暗紅色','暗粉紅色','暗黃色','暗白色','暗灰色','藍色','綠色','天藍色','紅色','粉紅色','黃色','白色'] # print information of this application print('#'*60) print('This app is used for translating English word to Chineses!') print('#'*60+'\n') # get word from Command line word = input("Enter a word (enter 'q' to exit): ") # main body while word != 'q': # 'q' to exit try: # 利用GET獲取輸入單詞的網頁信息 r = requests.get(url='http://dict.youdao.com/w/%s/#keyfrom=dict2.top' % word) # 利用BeautifulSoup將獲取到的文本解析成HTML soup = BeautifulSoup(r.text, "lxml") # 獲取字典的標籤內容 s = soup.find(class_='trans-container')('ul')[0]('li') # 隨機選擇輸出的顏色 random.shuffle(color_list) # 輸出字典的具體內容 for item in s: if item.text: cprint(item.text, color_list[0]) print('=' * 40 + '\n') except Exception as e: print("Sorry, there is a error!\n"+e) finally: word = input("Enter a word (enter 'q' to exit): ")
打包以下:this
運行結果url