python其实很简单

       Python作为动态语言非常的灵活,我们可以把更多的精力集中在编程对象和思维方法上,而不用去担心语法、类型等外在因素, 而Python清晰简洁的语法开发起来比Java简单的多,后面可以很明显的体现出来。

自己的体会:python对Excel和txt的处理非常方便。

python使用的版本及开发工具

  • python2和python3语法差别不大,设计思想差不多的。但是官方大概在2020年的时候会停止对python2的维护,最终将使用python3以后的版本进行推进,所以建议开始学习的话还是选择python3。
  • 开发工具:pycharm 配置简单、功能强大,并且语法的提示非常友好,和idea同出于一个公司
  • 支持的操作系统:windows,Linux,mac, 在linux操作系统下可以开辟自己的虚拟空间 并且后两者直接提供了运行环境,相比于php,java 还是很方便的。

python环境搭建

  python官网下载可执行的安装文件 Windows x86-64 executable installer 记得勾选路径选项,把路径添加到系统环境变量中。

python 虚拟环境的安装(https://www.jianshu.com/p/9f47a9801329)

python包的安装 
pip install 包名称

查看自己的环境安装包

pip freeze 这个特别重要的一个技巧

导出虚拟环境的依赖包
pip freeze > hello.txt

安装虚拟环境的依赖包
pip install -r hello.txt

python包的官方网址
https://pypi.python.org/pypi

python第一个小程序

这是用python实现的第一个经典小程序

print("hello world")

# -*- coding: utf-8 -*-
import datetime
print(datetime.datetime.now().strftime(format='%Y-%m-%d'))

#-*- coding:utf-8 -*-
#遍历任何一个可迭代对象
a=[1,2,34,4,5,6]
for i in a:
    print(i)
a='1231jeewe23432324'
for i in a:
    print(i)

import json
data = {"spam" : "foo", "parrot" : 42}
in_json=json.dumps(data)
print(type(in_json))
json_data=json.loads(in_json)
print(type(json_data))
'''
<class 'str'>
<class 'dict'>
'''
#网络访问,未曾定制任何参数
import requests
res=requests.get(url='https://my.oschina.net/u/3668329/blog/edit/1633070')
print(res.text)
完成请求

简单定制参数(如下)
import requests
headers={
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'
}
res=requests.get(url='https://www.baidu.com/',headers=headers,timeout=3)
print(res.text)

   

python的数据结构

数据主要分为:

整数型 ;数字的整数  
浮点型; 数字带小数
字符串; 用 ‘’ 或者 “” 引用的任意文本
布尔型;只有 True 和 False
数据结构分为:

列表 list
元祖 tuple
字典 dict
集合 set

python的有趣的小应用

1 微信小应用 itchat http://itchat.readthedocs.io/zh/latest/tutorial/tutorial0/

#-*- coding:utf-8 -*-
import itchat
itchat.auto_login(hotReload=True)
friends=itchat.get_friends()
for i in friends:
    print(i)
# 初始化计数器,有男有女,当然,有些人是不填的
male = female = other = 0
# 1表示男性,2女性
for i in friends[1:]:
    sex = i["Sex"]
    if sex == 1:
        male += 1
    elif sex == 2:
        female += 1
    else:
        other += 1
total = len(friends[1:])
print(total)
print( u"男性好友:%.2f%%" % (float(male) / total * 100))
print(u"女性好友:%.2f%%" % (float(female) / total * 100))
print(u"其他:%.2f%%" % (float(other) / total * 100))

itchat.run()

答案:
293
男性好友:59.04%
女性好友:35.15%
其他:5.80%

2 微信自动回复消息

# coding=utf8
import itchat, time
from itchat.content import *


@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
    for i in range(1000):
        itchat.send('%s' % ('新年快乐,祝你在新的一年里事业顺利,心想事成!'), msg['FromUserName'])
        time.sleep(1)


@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    msg['Text'](msg['FileName'])
    return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName'])


@itchat.msg_register(FRIENDS)
def add_friend(msg):
    itchat.add_friend(**msg['Text'])  # 该操作会自动将新好友的消息录入,不需要重载通讯录
    itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName'])


@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):
    if msg['isAt']:
        itchat.send(u'@%s\u2005I received: %s' % (msg['ActualNickName'], msg['Content']), msg['FromUserName'])


itchat.auto_login(hotReload=True)


itchat.run()

3 有趣的小案例 微信个性签名词云图

# coding:utf-8
import itchat
import re

# 先登录
itchat.auto_login(hotReload=True)

# 获取好友列表
friends = itchat.get_friends(update=True)[0:]
for i in friends:
    # 获取个性签名
    signature = i["Signature"]
print(signature)
# 先全部抓取下来
# 打印之后你会发现,有大量的span,class,emoji,emoji1f3c3等的字段,因为个性签名中使用了表情符号,这些字段都是要过滤掉的,写个正则和replace方法过滤掉

for i in friends:
# 获取个性签名
    signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji", "")
# 正则匹配过滤掉emoji表情,例如emoji1f3c3等
    rep = re.compile("1f\d.+")
    signature = rep.sub("", signature)
    print(signature)
# 接来下用jieba分词,然后制作成词云,首先要安装jieba和wordcloud库
#
# pip install jieba
# pip install wordcloud
#wordcloud 安装失败 http://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud

friends = itchat.get_friends(update=True)[0:]
tList = []
for i in friends:
    signature = i["Signature"].replace(" ", "").replace("span", "").replace("class", "").replace("emoji", "")
    rep = re.compile("1f\d.+")
    signature = rep.sub("", signature)
    tList.append(signature)

# 拼接字符串
text = "".join(tList)

# jieba分词
import jieba
wordlist_jieba = jieba.cut(text, cut_all=True)
wl_space_split = " ".join(wordlist_jieba)

# wordcloud词云
import matplotlib.pyplot as plt
from wordcloud import WordCloud

# 这里要选择字体存放路径,这里是Mac的,win的字体在windows/Fonts中
my_wordcloud = WordCloud(background_color="white", max_words=2000,
                         max_font_size=40, random_state=42,
                         font_path='C:\Windows\Fonts\STZHONGS.TTF').generate(wl_space_split)

plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
itchat.run()

如果有兴趣的话还可以扩展更多的东西

学习资料

廖雪峰的教程(重点推荐)

学习参考(https://github.com/lijin-THU/notes-python)

爬虫相关文档(非常方便的数据爬虫框架,文档相当齐全)

流行的数据分析库

NumPy是Python科学计算的基础包,它提供:

快速高效的多维数组对象ndarray;

直接对数组执行数学运算及对数组执行元素级计算的函数;

线性代数运算、随机数生成;
Pandas

Pandas主要提供快速便捷地处理结构化数据的大量数据结构和函数。

Matplotlib

Matplotlib是最流行的用于绘制数据图表的Python库。

当然还有很多非常实用的库。。。

猜你喜欢

转载自my.oschina.net/u/3798913/blog/1635280