一、分词 - jieba
- 优良的中文分词库,依附中文词库,利用词库确定汉子之间关联的概率,造成分词后果
import jiebaword = '平凡的中华人民共和国'jieba.cut(word)jieba.lcut(word)
二、词云库 - wordcloud
- 对数据中呈现频率较高的
关键词
生成的一幅图像,予以视觉上的突出
import jiebaimport numpy as npimport PIL.Image as Imagefrom wordcloud import WordClouddef run(word_path, picture_path): with open(word_path, 'r') as f: word = f.read() cut_word = ' '.join(jieba.cut(word)) color_mask = np.array(Image.open(picture_path)) word_cloud = WordCloud( # 设置字体,不指定就会呈现乱码 font_path='/System/Library/Fonts/PingFang.ttc', # 设置背景色 background_color='white', # 词云形态 mask=color_mask, # 容许最大词汇 max_words=120, # 最大号字体 max_font_size=2000 ).generate(cut_word) word_cloud.to_file('word_cloud.jpg') im = word_cloud.to_image() im.show()
三、可视化进度条 - tpdm
- 难看的进度条,不仅会让人一眼就晓得工作的进度,还可能让本人的情绪愉悦
from time import sleepfrom tqdm import tqdm# 这里同样的,tqdm就是这个进度条最罕用的一个办法# 外面存一个可迭代对象for i in tqdm(range(1, 500)): # 模仿你的工作 sleep(0.01)sleep(0.5)
四、柔美的表格 - PrettyTable
import prettytable as pt# 按行增加数据tb = pt.PrettyTable()tb.field_names = ['name', 'age', 'height', 'weight']tb.add_row(['亮仔', 25, 174, 65])tb.add_row(['程序员', 23, 164, 55])tb.add_row(['程序员亮仔', 27, 184, 69.5])print(tb)# +-----------+-----+--------+--------+# | name | age | height | weight |# +-----------+-----+--------+--------+# | 亮仔 | 25 | 174 | 65 |# | 程序员 | 23 | 164 | 55 |# | 程序员亮仔 | 27 | 184 | 69.5 |# +-----------+-----+--------+--------+
五、多过程 - multiprocessing
from multiprocessing import Processdef func(s): print(s)if __name__ == '__main__': process = [ Process(target=func, args=('1', )) Process(target=func, args=('2', )) ] [p.start() for p in process] [p.join() for p in process]
六、多线程 - threading
import threadingdef func(s): print(s)if __name__ == '__main__': thread = [ threading.Thread(target=func, args=('1', )) threading.Thread(target=func, args=('2', )) ] [t.start() for t in thread] [t.join() for t in thread]
七、谷歌翻译 - googletrans
from googletrans import Translatortranslator = Translator()# 未提供源语言以及翻译的最终语言,会主动翻译成英文translator.translate('안녕하세요.')# 通知它翻译成什么语言translator.translate('안녕하세요.', dest='ja')# 通知它源语言是什么translator.translate('程序员亮仔', src='zh-cn')# 语言检测t = ttranslator.detect('이 문장은 한글로 쓰여졌습니다.')t.lang
八、反复回调 - retrying
- 如果申请失败,咱们须要再从新进行进行申请,避免申请异样导致数据缺失
from retrying import retry@retry(stop_max_attempt_number=5)def say(): try: cxyliangzai except Exception as e: # 能够将谬误记录日志 print(e) raise say()
九、游戏开发 - pygame
- 实现 python 游戏的开发,能够开发各种大小型游戏
import pygame, sysfrom pygame.locals import * # 初始化pygamepygame.init() # 设置窗口的大小,单位为像素screen = pygame.display.set_mode((500,400), 0, 32) # 设置窗口的题目pygame.display.set_caption('用户事件监控') # 设置背景screen.fill((255, 255, 255)) # 程序主循环while True: # 获取事件 for event in pygame.event.get(): # 判断事件是否为退出事件 if event.type == QUIT: # 退出pygame pygame.quit() # 退出零碎 sys.exit() # 取得键盘按下的事件 if event.type == KEYDOWN: if(event.key==K_UP or event.key==K_w): print("上") if(event.key==K_DOWN or event.key==K_s): print("下") if(event.key==K_LEFT or event.key==K_a): print("左") if(event.key==K_RIGHT or event.key==K_d): print("右") # 按下键盘的Esc键退出 if(event.key==K_ESCAPE): # 退出pygame pygame.quit() # 退出零碎 sys.exit() # 取得鼠标以后的地位 if event.type ==MOUSEMOTION: print(event.pos) # 取得鼠标按下的地位 if event.type ==MOUSEBUTTONDOWN: print("鼠标按下:", event.pos) # 取得鼠标抬起的地位 if event.type ==MOUSEBUTTONUP: print("鼠标抬起:", event.pos) # 绘制屏幕内容 pygame.display.update()
十、绘图教程 - turtle
from turtle import *colors = ['red', 'purple', 'blue', 'green', 'yellow', 'orange']for x in range(360): pencolor(colors[x % 6]) width(x / 100 + 1) forward(x) left(59)
十一、数据分析 - pandas
- 数据分析解决库,为解决数据分析工作而创立的,可能疾速便捷地解决数据的函数和办法
import pandas as pdinfo = pd.read_csv("students.csv", encoding = "utf-8")# 查看数据框的一些属性:最大、最小、均值、四分位数等info.describe()# 空值相干的操作pin = info["pin"]pin_isnull = pd.isnull(pin) pin_isnull_list = info[pin_isnull] len(pin_isnull_list)# 缺失值相干操作, 简略的解决方法就是过滤掉null值books = info["life_cycle_books"]book_isnull = pd.isnull(books)book_list_isnull = info["life_cycle_books"][book_isnull == False]mean = sum(book_list_isnull) / len(book_list_isnull)# 删除缺失值, 所有行na_info = info.dropna(axis = 1)# 删除缺失值, 能够指定列na_info = info.dropna(axis = 0, subset = ["age", "name"])
十二、算法加密 - pycryto
- pycryto 能实现大抵 3 种类型的数据加密(单向加密、对称加密 和非对称加密),产生随机数,生成密钥对,数字签名
from Crypto.Hash import SHA256hash = SHA256.new()hash.update('Hello, World!')# 应用digest()办法加密digest = hash.digest()# 应用hexdigest()办法加密,该办法加密后是16进制的hexdigest = hash.hexdigest()print(digest, hexdigest)
十三、操作 win 电脑 - pywin32
- pywin32 包装了 Windows 零碎的 Win32 API,能创立和应用 COM 对象和图形窗口界面
import win32apiimport win32conhid = win32gui.WindowFromPoint((100, 100))# 获取窗口题目title = win32gui.GetWindowText(hid)# 获取窗口类名class_name = win32gui.GetClassName(hid)# 模仿鼠标在(400, 500)地位进行点击操作point = (400, 500)win32api.SetCursorPos(point)win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)
十四、主动程序测试 - Selenium
- Selenium 是一个用于 Web 应用程序测试的工具。Selenium 测试间接运行在浏览器中,就像真正的用户在操作一样
from selenium import webdriverfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.wait import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC # 初始化谷歌浏览器driver = webdriver.Chrome() # 最大化窗口driver.maximize_window() # 关上头条登陆网址driver.get('https://sso.toutiao.com') # 期待某个元素是否呈现WebDriverWait(self.driver, 10).until( EC.text_to_be_present_in_element((By.XPATH, '//*[@id="mobile-code-get"]/span'), u'发送')) # 实例化鼠标操作action = ActionChains(self.driver) # 按住滑块action.click_and_hold(self.driver.find_element_by_xpath('//*[@id="captcha_container"]')).perform() # 将滑块挪动x的间隔action.move_by_offset(xoffset=x, yoffset=0).perform() # 开释滑块action.release().perform()
十五、音频播放 - mp3play
- 一款超级小型的音频操作库,能够实现播放音乐,按空格键实现暂停和播放的切换
import mp3playclip = mp3play.load('music.mp3')clip.play()
十六、网页解析 - BeautifulSoup
from bs4 import BeautifulSoupsoup = BeautifulSoup('<p class="name nickname user"><b>i am cxyliangzai</b></p>', 'html.parser')#获取整个p标签的html代码print(soup.p)#获取b标签print(soup.p.b)#获取p标签内容,应用NavigableString类中的string、text、get_text()print(soup.p.text)#返回一个字典,外面是多有属性和值print(soup.p.attrs)#查看返回的数据类型print(type(soup.p))#依据属性,获取标签的属性值,返回值为列表print(soup.p['class'])#给class属性赋值,此时属性值由列表转换为字符串soup.p['class']=['Web','Site']print(soup.p)
十七、日志解决 - logging
import logginglogging.basicConfig(filename='logging.text', level=logging.DEBUG)logging.debug('It is a debug')logging.info('It is a info')logging.warning('It is a warning')
十八、图像处理 - PIL
- 非常适合于图像归档以及图像的批处理工作。能够应用 PIL 创立缩略图,转换图像格式,打印图像等等
from PIL import Imageim = Image.open("picture.jpg")new_im = im.convert('L')print(new_im.mode)new_im.show()
十九、发送邮件 - yagmail
- 是一种非常简单用来实现主动发邮件性能的包,能够实现给单人或者多人同时发送邮件
import yagmail# 链接邮箱服务器yag = yagmail.SMTP( user='邮箱地址', password='登录明码', host='smtp.163.com')# 邮箱注释contents = ['邮件第一行内容', '邮件第二行内容', '邮件第三行内容']# 给用户发送邮件并增加多个附件yag.send(['指标邮箱地址1', '指标邮箱地址2', '指标邮箱地址3'], '邮件题目', contents, ['c://附件.pdf', 'c://picture.jpg'])
二十、源码打包 - pyinstaller
pyinstaller -F -w -p ./lib -i logo.ico main.py