python is actually very simple

       As a dynamic language, Python is very flexible. We can focus more on programming objects and thinking methods without worrying about external factors such as syntax and types. Python's clear and concise syntax is much simpler to develop than Java. It can be clearly manifested later.

My own experience: python is very convenient for processing Excel and txt.

The version and development tools used by python

  • There is little difference in syntax between python2 and python3, and the design ideas are similar. However, the official will stop the maintenance of python2 in about 2020, and will eventually use the later version of python3 to advance, so it is recommended to choose python3 if you start learning.
  • Development tools: pycharm is simple to configure, powerful, and has very friendly syntax prompts. It is from the same company as idea.
  • Supported operating systems: windows, Linux, mac, under the linux operating system, you can open up your own virtual space and the latter two directly provide the operating environment, which is very convenient compared to php and java.

python environment construction

  Download the executable installation file from the python official website Windows x86-64 executable installer Remember to check the path option and add the path to the system environment variable.

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's first applet

This is the first classic applet implemented in 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 data structure

数据主要分为:

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

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

Interesting little application of python

1 WeChat mini-app 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 WeChat auto-reply messages

# 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 Interesting little cases WeChat personality signature word cloud

# 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()

If you are interested, you can expand more

learning materials

Liao Xuefeng's tutorial (key recommendation)

Learning reference (https://github.com/lijin-THU/notes-python)

Crawler related documents (very convenient data crawler framework, the documentation is quite complete)

Popular Data Analysis Libraries

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

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

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

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

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

Matplotlib

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325441725&siteId=291194637