• 干货合集│最好用的 python 库都在这


    一、分词 - jieba#

    • 优秀的中文分词库,依靠中文词库,利用词库确定汉子之间关联的概率,形成分词结果
    import jieba
    
    word = '伟大的中华人民共和国'
    
    jieba.cut(word)
    jieba.lcut(word)
    

    二、词云库 - wordcloud#

    • 对数据中出现频率较高的 关键词 生成的一幅图像,予以视觉上的突出
    import jieba
    import numpy as np
    import PIL.Image as Image
    from wordcloud import WordCloud
    
    def 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 sleep
    from 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 Process
    
    def 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 threading
    
    def 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 Translator
    
    translator = 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, sys
    from pygame.locals import *
     
    # 初始化pygame
    pygame.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 pd
    
    info = 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 SHA256
    
    hash = 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 win32api
    import win32con
    
    hid = 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 webdriver
    from selenium.webdriver import ActionChains
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.wait import WebDriverWait
    from 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 mp3play
    
    clip = mp3play.load('music.mp3')
    clip.play()
    

    十六、网页解析 - BeautifulSoup#

    • 是一个网页解析库,能够快速的分析网页结构
    from bs4 import BeautifulSoup
    
    soup = 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 logging
    
    logging.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 Image
    
    im = 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#

    • 将源码打包成exe文件,直接在window上运行
    pyinstaller -F -w -p ./lib -i logo.ico main.py
    
  • 相关阅读:
    TypeScript 地图标记案例
    pod(一):Kubernetes(k8s)创建pod的两种方式
    java spring security oauth2 动态 修改当前登录用户的基础信息以及权限2.0(无需重新登录)
    【一刷《剑指Offer》】面试题 9:斐波那契数列(扩展:青蛙跳台阶、矩阵覆盖)
    [ARC098F] Donation(找性质+点 Kruskal 重构树)
    Vue 3的高颜值UI组件库
    后端总说他啥也没动,我从线上调了一下测试接口,你再说一句动没动
    云原生之旅 - 13)基于 Github Action 的自动化流水线
    huggingface.co 下载模型文件,死活找不到文件,也没报其他错误。原来是多了个%号
    从零开始利用MATLAB进行FPGA设计(一):建立脉冲检测模型的Simulink模型2
  • 原文地址:https://www.cnblogs.com/cxyliangzai/p/16360794.html