竞争无处不在,青春永不言败!专业撸代码,副业修bug

Talk is cheap , show me the code!



python 有趣的库练习

这里会将看到别人玩过有趣的实践并记录下来,会是一个长期更新的过程...
以下大部分均非原创变化自网络,只是觉得有趣便记录下来了,如有侵权,请告知删除...

自动化脚本。。。

20个必不可少的Python库
转载:http://www.python123.org/tutorials/58b41f2a28c8f30100bd41dc

读者们好。今天我将介绍20个属于我常用工具的Python库,我相信你看完之后也会觉得离不开它们。他们是:

Requests.Kenneth Reitz写的最富盛名的http库。每个Python程序员都应该有它。
Scrapy.如果你从事爬虫相关的工作,那么这个库也是必不可少的。用过它之后你就不会再想用别的同类库了。
wxPython.Python的一个GUI(图形用户界面)工具。我主要用它替代tkinter。你一定会爱上它的。
Pillow.它是PIL(Python图形库)的一个友好分支。对于用户比PIL更加友好,对于任何在图形领域工作的人是必备的库。
SQLAlchemy.一个数据库的库。对它的评价褒贬参半。是否使用的决定权在你手里。
BeautifulSoup.我知道它很慢,但这个xml和html的解析库对于新手非常有用。
Twisted.对于网络应用开发者最重要的工具。它有非常优美的api,被很多Python开发大牛使用。
NumPy.我们怎么能缺少这么重要的库?它为Python提供了很多高级的数学方法。
SciPy.既然我们提了NumPy,那就不得不提一下SciPy。这是一个Python的算法和数学工具库,它的功能把很多科学家从Ruby吸引到了Python。
matplotlib.一个绘制数据图的库。对于数据科学家或分析师非常有用。
Pygame.哪个程序员不喜欢玩游戏和写游戏?这个库会让你在开发2D游戏的时候如虎添翼。
Pyglet.3D动画和游戏开发引擎。非常有名的Python版本Minecraft就是用这个引擎做的。
pyQT.Python的GUI工具。这是我在给Python脚本开发用户界面时次于wxPython的选择。
pyGtk.也是Python GUI库。很有名的Bittorrent客户端就是用它做的。
Scapy.用Python写的数据包探测和分析库。
pywin32.一个提供和windows交互的方法和类的Python库。
nltk.自然语言工具包。我知道大多数人不会用它,但它通用性非常高。如果你需要处理字符串的话,它是非常好的库。但它的功能远远不止如此,自己摸索一下吧。
nose.Python的测试框架。被成千上万的Python程序员使用。如果你做测试导向的开发,那么它是必不可少的。
SymPy.SymPy可以做代数评测、差异化、扩展、复数等等。它封装在一个纯Python发行版本里。
IPython.怎么称赞这个工具的功能都不为过。它把Python的提示信息做到了极致。包括完成信息、历史信息、shell功能,以及其他很多很多方面。一定要研究一下它。
我希望你喜欢今天的文章。请在评论区留下你的看法。如果你觉得有哪个库被遗漏了请在评论里告诉我,我会把它加上去。请留意下一期的文章。

英文原文:https://pythontips.com/2013/07/30/20-python-libraries-you-cant-live-without/ 译者:shambala

python gui 之 wxpython

# -*- coding: utf-8 -*-
__author__ = 'Frank Li'
import wx

app = wx.App()
frame = wx.Frame(None,title = "Gui Test Editor",pos = (1000,200),size = (500,400))

path_text = wx.TextCtrl(frame,pos = (5,5),size = (350,24))
open_button = wx.Button(frame,label = "打开",pos = (370,5),size = (50,24))
save_button = wx.Button(frame,label = "保存",pos = (430,5),size = (50,24))
content_text= wx.TextCtrl(frame,pos = (5,39),size = (475,300),style = wx.TE_MULTILINE)  # wx.TE_MULTILINE可以实现换行功能,若不加此功能文本文档显示为一行显示
frame.Show()
app.MainLoop()

QQ 简单聊天接入图灵机器人

# -*- coding: utf-8 -*-
__author__ = 'Frank Li'

from qqbot import QQBotSlot as qqbotslot,RunBot
# import turing
from random import choice
from qqbot import qqbotsched
import requests
import json

key = '2e30d196049c4751b0254604a34ee858'

# QQBot 就是一个qq登录的类
# myqqbot = QQBot()   #实例化一个qq实例
# myqqbot.Login('57xxxx')  #进行登录,执行这条命令,系统会弹出一个二维码,我们扫码登录
# myqqbot.pollForever()

def main(info):
    url = 'http://www.tuling123.com/openapi/api?key='+key+'&info='+info
    res = requests.get(url)
    res.encoding = 'utf-8'
    jd = json.loads(res.text)
    return jd['text']

@qqbotsched(hour='11,16', minute='40')
def mytask(bot):
    resturant_list = ['煲仔饭','黄焖鸡','浏阳蒸菜','津市牛肉粉','更多未知']
    gl = bot.List('group', '守望把开水')
    if gl is not None:
        for group in gl:
            bot.SendTo(group, '哔哔哔,同志们,开饭啦啦啦啦啦啦!!!')
            bot.SendTo(group, '今天随机餐馆--\\>'+choice(resturant_list))

friend = []

@qqbotslot
def onQQMessage(bot, contact, member, content):
    # print(bot.List('group'))
    if bot.isMe(contact,member):
        # print('is me!!!')
        pass
    elif '@ME' in content:
        bot.SendTo(contact, '嗨! '+member.name + ',艾特我干嘛呢?')

    elif  contact.ctype == 'buddy' and "--stop" == content:
        if contact.mark in friend:
            friend.remove(contact.mark)
            bot.SendTo(contact, '关闭机器人')

    elif contact.ctype == 'buddy' and "--start" == content and '哈哈,哈哈哈,哈哈哈哈哈' != contact.mark:
        if contact.mark not in friend:
            friend.append(contact.mark)
            bot.SendTo(contact, '欢迎使用机器人')

    elif contact.ctype == 'buddy' and not bot.isMe(contact,member):
        daan = main(content)
        bot.SendTo(contact, '🍅' + daan)
        print(contact.name,contact.ctype,contact.nick)

    elif contact.ctype=='group' and contact.name == '守水' and (member.name=='守望' or member.name=='李') and '关闭机器人' == content:
        bot.SendTo(contact,'机器人已关闭....')
        bot.Stop()

    elif contact.ctype == 'group' and contact.name == '守望 开水' and '开启机器人' == content:
        bot.SendTo(contact, '机器人已开启...实际也未关闭...')

    elif contact.ctype == 'group' and contact.name == '测试人生' and not bot.isMe(contact,member):
        daan = main(content)
        bot.SendTo(contact, '🍅' + daan)

    elif contact.ctype == 'group' and contact.name == '机器人聊天' and not bot.isMe(contact,member):
        daan = main(content)
        bot.SendTo(contact, '🍅' + daan)

    elif contact.ctype == 'group' and contact.name == '守、来杯开水' and not bot.isMe(contact,member):
        daan = main(content)
        bot.SendTo(contact, '🍅' + daan)

    elif contact.ctype == 'buddy' and contact.mark in friend:                        #对指定的人发自动回复
        daan = main(content)
        bot.SendTo(contact, '🍅'+daan)
        print(contact.name, contact.ctype, contact.nick, contact.uin, contact.mark)
    elif 'mememeda' == content:
        print("关闭机器人")
        bot.Stop()



RunBot()

微信简单聊天接入图灵机器人 wxpy , 扫码登录

# -*- coding: utf-8 -*-
__author__ = 'Frank Li'
from wxpy import *

#微信登陆

bot = Bot()

# 定位公司群
company_group = bot.groups().search('交流')[0]
# 定位老板
# boss = company_group.search(u'小白龙')[0]
# 初始化图灵机器人 (API key 申请: http://tuling123.com)
tuling = Tuling(api_key='8edce3ce905a4c1dbb965e6b35c3834d')

#自动回复所有消息

@bot.register(company_group,msg_types=TEXT)

def auto_reply_all(msg):
    tuling.do_reply(msg)

# 定位家庭群
family_group = bot.groups().search('老李家')[0]
# 开始运行
@bot.register(family_group,msg_types=TEXT)

def auto_reply_all(msg):
    tuling.do_reply(msg)

# 定位家庭群
test_group = bot.groups().search('测试机器人')[0]
# 开始运行
@bot.register(test_group,msg_types=TEXT)

def auto_reply_all(msg):
    tuling.do_reply(msg)

# 定位家庭群
robot_group = bot.groups().search('机器人')[0]
# 开始运行
@bot.register(robot_group,msg_types=TEXT)

def auto_reply_all(msg):
    tuling.do_reply(msg)

bot.join()

opencv 的安装与使用

pip install opencv-python

拍照

# -*- coding: utf-8 -*-
__author__ = 'Frank Li'
import cv2

cap = cv2.VideoCapture(0)
while(1):
    # get a frame
    ret, frame = cap.read()
    # show a frame
    cv2.imshow("capture", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        cv2.imwrite("D:/gom/cap.jpeg", frame)
        break
cap.release()
cv2.destroyAllWindows()

仅供娱乐的暴力跑字典破解方式,真要如此实际操作得疯了。。。

# -*- coding: utf-8 -*-
__author__ = 'Frank Li'

# coding:utf-8
import time  #时间
import pywifi  #破解wifi
from pywifi import const  #引用一些定义
from asyncio.tasks import sleep
class PoJie():
    def __init__(self,path):
        self.file=open(path,"r",errors="ignore")
        wifi = pywifi.PyWiFi() #抓取网卡接口
        self.iface = wifi.interfaces()[0]#抓取第一个无限网卡
        self.iface.disconnect() #测试链接断开所有链接

        time.sleep(1) #休眠1秒

        #测试网卡是否属于断开状态,
        assert self.iface.status() in\
            [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]

    def readPassWord(self):
            print("开始破解:")
            while True:

                try:
                    myStr =self.file.readline()
                    if not myStr:
                        break
                    bool1=self.test_connect(myStr)
                    if bool1:
                        print("密码正确:",myStr)
                        break
                    else:
                        print("密码错误:"+myStr)
                    sleep(3)
                except:
                    continue

    def test_connect(self,findStr):#测试链接

        profile = pywifi.Profile()  #创建wifi链接文件
        profile.ssid ="360WiFi-CE71E1" #wifi名称
        profile.auth = const.AUTH_ALG_OPEN  #网卡的开放,
        profile.akm.append(const.AKM_TYPE_WPA2PSK)#wifi加密算法
        profile.cipher = const.CIPHER_TYPE_CCMP    #加密单元
        profile.key = findStr #密码

        self.iface.remove_all_network_profiles() #删除所有的wifi文件
        tmp_profile = self.iface.add_network_profile(profile)#设定新的链接文件
        self.iface.connect(tmp_profile)#链接
        time.sleep(5)
        if self.iface.status() == const.IFACE_CONNECTED:  #判断是否连接上
            isOK=True
        else:
            isOK=False
        self.iface.disconnect() #断开
        time.sleep(1)
        #检查断开状态
        assert self.iface.status() in\
            [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]

        return isOK


    def __del__(self):
        self.file.close()

path=r"E:\\BaiduNetdiskDownload\\wpapasswd\\cnpassword.txt" # 密码字典有百度云盘地址,可留言索取...
start=PoJie(path)
start.readPassWord()

链接 密码:16sl

为了方便导出 csv 文件,写了个小程序可用 pyinstaller 打包 exe 可执行文件

# -*- coding: utf-8 -*-
__author__ = 'Frank Li'
import psycopg2
from pandas import DataFrame
from json import loads
from  pprint import pprint
class DBUtils(object):
    db_info = {}

    def __init__(self, **kw):
        # 如果没有传数据库信息过来采用默认的信息
        self._schema_name = DBUtils.db_info['schema_name']
        self._table_name = DBUtils.db_info['table_name']
        self._db_name = DBUtils.db_info['database']
        self._user = DBUtils.db_info['user']
        self._password = DBUtils.db_info['password']
        self._host = DBUtils.db_info['host']
        self._port = DBUtils.db_info['port']

        # 如果有传数据库信息过来采用传过来的信息
        for key, value in kw.items():
            if key == 'db_name':
                self._db_name = value
            if key == 'host':
                self._host = value
            if key == 'port':
                self._port = value
            if key == 'user':
                self._user = value
            if key == 'password':
                self._password = value
            if key == 'schema_name':
                self._schema_name = value
            if key == 'table_name':
                self._table_name = value

    def get_conn(self):
        conn = psycopg2.connect(dbname=self._db_name, host=self._host,
                                port=self._port, user=self._user, password=self._password)
        return conn

    def get_dataframe(self):
        sql = "select * from " + self._schema_name + '.' + self._table_name
        print(sql)
        conn = self.get_conn()
        cur = conn.cursor()
        cur.execute(sql)
        rows = cur.fetchall()
        df = DataFrame(list(rows))
        return df
    def to_csv(self,df):
        df.to_csv('output.csv',header=False,index=False,encoding='utf-8')

if __name__ == '__main__':
    with open('./config.json', 'r', encoding='utf-8') as config:
        text = config.read()
        database_dict = loads(text)
        pprint(database_dict)
    dbutils = DBUtils(**database_dict)
    dbutils.to_csv(dbutils.get_dataframe())
    print('\n\nexport success!')

对应 config.json 文件如下格式

{
	"database": "xxx",
	"user": "frank",
	"password": "frankxxx",
	"host": "dev-xxxredshift.amazonaws.com",
	"port": "5439",
	"schema_name": "public",
	"table_name": "xxx_report"
}

word 转换为 txt 文档

# -*- coding: utf-8 -*-
__author__ = 'Frank Li'
import os
from os import path
from win32com import client as wc
from win32com.client.gencache import EnsureDispatch

'''
功能描述: word 文件转存 txt, 默认保存在 根目录下, 支持自定义
参数描述: 1 filePath 文件路径 2 savePath: 保存路径

'''
def word2txt(filePath, savePath=''):
    # 1 切分文件路径为 文件目录和文件名
    dir_path, src_file_name = path.split(filePath)
    #2 修改切分后的文件后缀
    file_name, file_ext = path.splitext(src_file_name)

    if file_ext not in ('.doc','.docx'):
        raise BaseException(' 文件类型不支持 !仅支持 doc , docx 类型')
    # 3 设置新的文件保存路径
    tar_file_name = path.join(dir_path, file_name+'.txt')
    # 4 加载文本提取的处理程序
    word_app = EnsureDispatch('kwps.application')
    res_txt = word_app.Documents.Open(filePath)

    print(type(res_txt))
    print(tar_file_name)
    # 5 保存文本信息
    res_txt.SaveAs(tar_file_name, 4) # 参数 4 代表抽取文本
    res_txt.Close()


if __name__ == '__main__':
    word2txt(r'C:\Users\FrankLi\Downloads\[小学]优美的句子.doc','')

提取 pdf

pip install pdfminer3k
posted @ 2018-09-29 09:54  云雾散人  阅读(1142)  评论(0编辑  收藏  举报

Your attitude not your aptitude will determine your altitude!

如果有来生,一个人去远行,看不同的风景,感受生命的活力!