“Except Python can’t have kids, Python can do everything from flirt to play x! Everything!”
Python;
Python jumps to 4999;
Python;
Python;
Python…
Python operations:
1. Python lets you never miss a red envelope
Python, develop a small wechat assistant, from now on do not have to worry about missing a huge red envelope!
1. It is troublesome to receive the red envelope message and get the data directly from wechat on the mobile phone. The mainstream method is to get the data through wechat web version.
2, send a notice, the simplest notice method is to make a sound, if not enough, you can play a window.
Open wechat on your phone
Poco (text = ‘WeChat). Click ()
Get the name of all group chats in the current page
Chat_msg = poco(name=’com.tencent.mm:id/d1v’).offspring(‘com.tencent.mm:id/b6e’)
Gets the names of all group chats on the current page
Chat_names = []
Chat_names = list(map(lambda x: x.get_text(), Chat_msg))
Specify the group chat name for grabbing red packets
Chat = input(‘ please specify group chat name ‘)
if chat in Chat_names:
index = Chat_names.index(chat)
Click to enter the specified group chat
Chat_msg[index].click()
msg_list = poco(“android.widget.ListView”).children()
Traverse the message and look for the red envelope
for msg in msg_list:
The logo of wechat red envelope
LuckyMoney = msg.offspring(‘com.tencent.mm:id/aql’)
The logo of an expired red envelope (such as one that has been received or received)
Invalid = msg.offspring(‘com.tencent.mm:id/aqk’)
Decide if the red envelope is valid and grab it!
if LuckyMoney:
pass
# Traverse the message and look for red packets
If invalid.exists () and (invalid.get_text ()==’ received ‘or invalid.get_text ()==’ received ‘):
Print (f’ f’) ‘)
continue
else:
Print (f’ find a new red envelope, grab! ‘)
poco(“com.tencent.mm:id/d1v”)
msg.click()
click_open = poco(“com.tencent.mm:id/d02”)
if click_open.exists():
click_open.click()
keyevent(‘BACK’)
# initializer
from airtest.core.api import *
auto_setup(file)
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
2. Python helps you grab train tickets
Python is not only good at snatching red packets, but also good at snatching train tickets. You may have bought your ticket from a scalper with Python.
Python3 captures the ticket information of 12306 website, timely reminder, automatic order.
from splinter.browser import Browser
from time import sleep
import traceback
class Buy_Tickets(object):
Define instance properties, initialize
def init(self, username, passwd, order, passengers, dtime, starts, ends):
self.username = username
self.passwd = passwd
Number of trains, 0 for all trains, from top to bottom, 1 for all trains, and so on
self.order = order
Passenger name
self.passengers = passengers
The beginning and the end
self.starts = starts
self.ends = ends
The date of
self.dtime = dtime
self.xb = xb
self.pz = pz
Self. Login_url = ‘kyfw. 12306. Cn/otns/login/I… ‘
Self. InitMy_url = ‘kyfw. 12306. Cn/otns/index/I… ‘
Self. Ticket_url = ‘kyfw. 12306. Cn/otns/leftTic… ‘
self.driver_name = ‘chrome’
self.executable_path = ‘C:\Python36\Scripts\chromedriver.exe’
Implementation of Login Function
def login(self):
self.driver.visit(self.login_url)
self.driver.fill(‘loginUserDTO.user_name’, self.username)
sleep(1)
self.driver.fill(‘userDTO.password’, self.passwd)
sleep(1)
Print (‘ Please enter the verification code… ‘)
while True:
if self.driver.url ! = self.initMy_url:
sleep(1)
else:
break
Realization of ticket buying function
def start_buy(self):
self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path)
# Window size manipulation
self.driver.driver.set_window_size(700, 500)
self.login()
self.driver.visit(self.ticket_url)
try:
Print (‘ Start buying tickets… ‘)
Loading query Information
self.driver.cookies.add({“_jc_save_fromStation”: self.starts})
self.driver.cookies.add({“_jc_save_toStation”: self.ends})
self.driver.cookies.add({“_jc_save_fromDate”: self.dtime})
self.driver.reload()
count = 0
if self.order ! = 0:
while self.driver.url == self.ticket_url:
Self. Driver. Find_by_text (” query “). Click ()
count += 1
Print (‘ %d ‘) ‘ % count)
try:
Self. Driver. Find_by_text (‘ reservations’) [self. The order – 1]. The click ()
Sleep (1.5)
except Exception as e:
print(e)
Print (‘ Booking failed… ‘)
continue
else:
while self.driver.url == self.ticket_url:
Self. Driver. Find_by_text (” query “). Click ()
count += 1
Print (‘ %d ‘) ‘ % count)
try:
For I in self.driver.find_by_text(‘ booking ‘):
i.click()
sleep(1)
except Exception as e:
print(e)
Print (‘ Booking failed… ‘)
continue
Print (‘ Start booking… ‘)
sleep(1)
Print (‘ Select user… ‘)
for p in self.passengers:
self.driver.find_by_text(p).last.click()
Sleep (0.5)
if p[-1] == ‘)’:
self.driver.find_by_id(‘dialog_xsertcj_ok’).click()
Print (‘ Submit order… ‘)
sleep(1)
self.driver.find_by_text(self.pz).click()
sleep(1)
self.driver.find_by_text(self.xb).click()
sleep(1)
self.driver.find_by_id(‘submitOrder_id’).click()
sleep(2)
Print (‘ Confirm seat selection… ‘)
self.driver.find_by_id(‘qr_submit_id’).click()
Print (‘ Order successful… ‘)
except Exception as e:
print(e)
if name == ‘main‘:
The user name
username = ‘xxxx’
password
password = ‘xxx’
Train selection, 0 represents all trains
order = 2
Passengers = [‘ xiaohong ‘, ‘xiaoming ‘]
Passengers = [‘ ding Xiaohong ‘, ‘DING Xiaoming ‘]
Select * from (select * from (select * from))
Date, format: ‘2018-01-20’
dtime = ‘2018-01-19’
Origin (Cookie value required)
Starts = ‘% U5434 % U5821 %2CWUY’ #
Destination (cookie value required)
Ends = ‘%u897F%u5B89%2CXAY’ #
Xb =[‘ xb ‘]
Pz =[‘ adult ticket ‘]
Buy_Tickets(username, password, order, passengers, dtime, starts, ends).start_buy()
3. Python helps you choose a house
Python script, crawl the listing information of a rental website, use Autonavi’S JS API to mark the listing location on the map, and draw a range within 1 hour from the workplace.
1.requests for past web content
2.BeautifulSoup
import time
import pymssql
import requests
from bs4 import BeautifulSoup
wh.lianjia.com/zufang/
Get the following content in the URL
def get_page(url):
responce = requests.get(url)
soup = BeautifulSoup(responce.text,’lxml’)
return soup
The function is to get the links of all the rental pages in the list, and return a list of links
def get_links(url):
responce = requests.get(url)
soup = BeautifulSoup(responce.text,’lxml’)
link_div = soup.find_all(‘div’,class_ = ‘pic-panel’)
links = [div.a.get(‘href’) for div in link_div]
return links
Collect information about a house
def get_house_info(house_url):
soup = get_page(house_url)
price = soup.find(‘span’,class_=’total’).text
unit = soup.find(‘span’,class_= ‘unit’).text[1:-1]
area = soup.find(‘p’, class_ = ‘lf’).text
house_info= soup.find_all(‘p’,class_ = ‘lf’)
Area = house_info[0]. Text [3:] #
layout = house_info[1].text[5:]
info={
‘price: price,
‘unit: the unit,
‘area: area.
‘family’ : layout
}
return info
# link database
Server =”192.168.xx.xx” # change your server information
user=”liujiepeng”
Password =” XXXXX “# own database user name and password
conn=pymssql.connect(server,user,password,database=”house”)
def insert(conn,house):
# sql_values = values. The format (house [‘ price ‘], house [‘ units’], house [‘ area ‘],
# house [‘ family ‘])
sql = “insert into [house]. Dbo. Lianjia (price, unit, area, layout) values (‘ % s’, ‘% s’,’ % s’, ‘% s’) “% (house/” price”, “house/” unit”, “house/” area”, “house []” family” )
print(sql)
Cursor = conn.cursor() # cursor opens a new window
#cursor1 = conn.cursor()
Cursor.execute (SQL) # Execute SQL statements
Conn.mit () # commit to update SQL statement
links = get_links(‘wh.lianjia.com/zufang/’)
count = 1
for link in links:
#time.sleep(2)
Print (‘ fetch data successfully ‘)
house = get_house_info(link)
insert(conn,house)
Print (” %s “) %(count))
count = count+1
# print (house (” price “), end = ‘\ r’)
4. Python retrieves the goddess retraction message
“YY”? Did she post something, and then when you asked her, she said nothing.
Python, you can make a program to collect the information withdrawn from private chat and send it to the personal wechat file transfer assistant.
5. Write your own games in Python
Writing a few games in Python is just a few dozen lines of code, like writing a snake!
Python will be at the top of the list all year round, and it will be fully automatic. It’s fun!
from future import print_function
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import math
import time
import os
import cv2
import datetime
Scale = 0.25
template = cv2.imread(‘character.png’)
template = cv2.resize(template, (0, 0), fx=scale, fy=scale)
template_size = template.shape[:2]
def search(img):
result = cv2.matchTemplate(img, template, cv2.TM_SQDIFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
cv2.rectangle(img, (min_loc[0], min_loc[1]), (min_loc[0] + template_size[1], min_loc[1] + template_size[0]), (255, 0, 0), (4)
return img, min_loc[0] + template_size[1] / 2, min_loc[1] + template_size[0]
def pull_screenshot():
filename = datetime.datetime.now().strftime(“%H%M%S”) + ‘.png’
os.system(‘mv autojump.png {}’.format(filename))
os.system(‘adb shell screencap -p /sdcard/autojump.png’)
os.system(‘adb pull /sdcard/autojump.png .’)
def jump(distance):
Press_time = distance * 1.35
press_time = int(press_time)
cmd = ‘adb shell input swipe 320 410 320 410 ‘ + str(press_time)
print(cmd)
os.system(cmd)
def update_data():
global src_x, src_y
img = cv2.imread(‘autojump.png’)
img = cv2.resize(img, (0, 0), fx=scale, fy=scale)
img, src_x, src_y = search(img)
return img
fig = plt.figure()
index = 0
pull_screenshot()
img = update_data()
update = True
im = plt.imshow(img, animated=True)
def updatefig(*args):
global update
if update:
time.sleep(1)
pull_screenshot()
im.set_array(update_data())
update = False
return im,
def onClick(event):
global update
global src_x, src_y
dst_x, dst_y = event.xdata, event.ydata
distance = (dst_x – src_x)**2 + (dst_y – src_y)**2
Distance = (distance ** 0.5)/scale
print(‘distance = ‘, distance)
jump(distance)
update = True
fig.canvas.mpl_connect(‘button_press_event’, onClick)
ani = animation.FuncAnimation(fig, updatefig, interval=5, blit=True)
plt.show()
#! /usr/bin/env python
import pygame,sys,time,random
from pygame.locals import *
Define color variables
RedColour = pygame. Color (0, 255)
BlackColour = pygame. Color (0, 0)
WhiteColour = pygame. Color (255255255).
GreyColour = pygame. Color (150150150).
Define the gameOver function
def gameOver(playSurface):
gameOverFont = pygame.font.Font(‘arial.ttf’,72)
gameOverSurf = gameOverFont.render(‘Game Over’, True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
pygame.quit()
sys.exit()
Defining the main function
def main():
Initialize the pygame
pygame.init()
fpsClock = pygame.time.Clock()
Create the PyGame display layer
PlaySurface = pygame. Display. Set_mode ((640480))
pygame.display.set_caption(‘Raspberry Snake’)
Initialize a variable
SnakePosition = [100100]
SnakeSegments = [[100100], [80100], [60100]]
RaspberryPosition = [300300]
raspberrySpawned = 1
direction = ‘right’
changeDirection = direction
while True:
Detect PyGame events such as keystrokes
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
Judge keyboard events
if event.key == K_RIGHT or event.key == ord(‘d’):
changeDirection = ‘right’
if event.key == K_LEFT or event.key == ord(‘a’):
changeDirection = ‘left’
if event.key == K_UP or event.key == ord(‘w’):
changeDirection = ‘up’
if event.key == K_DOWN or event.key == ord(‘s’):
changeDirection = ‘down’
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
Determine if the input is in the opposite direction
if changeDirection == ‘right’ and not direction == ‘left’:
direction = changeDirection
if changeDirection == ‘left’ and not direction == ‘right’:
direction = changeDirection
if changeDirection == ‘up’ and not direction == ‘down’:
direction = changeDirection
if changeDirection == ‘down’ and not direction == ‘up’:
direction = changeDirection
Move the coordinates of the snake head in the direction
if direction == ‘right’:
snakePosition[0] += 20
if direction == ‘left’:
snakePosition[0] -= 20
if direction == ‘up’:
snakePosition[1] -= 20
if direction == ‘down’:
snakePosition[1] += 20
Increase the length of the snake
snakeSegments.insert(0,list(snakePosition))
Determine if you’ve eaten a raspberry
if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
If you eat a raspberry, you regenerate it
if raspberrySpawned == 0:
X = random. Randrange aiaa (1)
Y = random. Randrange (1, 24)
raspberryPosition = [int(x20),int(y20)]
raspberrySpawned = 1
Draw the PyGame display layer
playSurface.fill(blackColour)
for position in snakeSegments:
Pygame. The draw. The rect (playSurface whiteColour, the rect (position [0], the position [1], 20, 20))
Pygame. The draw. The rect (playSurface redColour, the rect (raspberryPosition [0], raspberryPosition [1], 20, 20))
Refresh the PyGame display layer
pygame.display.flip()
To determine death.
if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver(playSurface)
if snakePosition[1] > 460 or snakePosition[1] < 0:
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
gameOver(playSurface)
Control game Speed
fpsClock.tick(5)
if name == “main“:
main()
Python crawls the information you want
Python crawls the movie to analyze the movie review and uses the word cloud to display the effect:
7. Look at your circle of friends
After Python, you play wechat, others also play wechat.
. Is performance going to creep up?
8. Python makes its own small animations
MV, become the big guy of B station, use OpenCV to process picture and video, turn the video into character painting sequence, and then play character animation in the terminal.
9. Python authentication
What else can Python be used for
Emmm jian huang!
Python3 identifies if an image is pornographic, and PIL, an image processing library, writes an algorithm to divide the skin area of the image.
Python 3 basics, skin color pixel detection and skin region segmentation algorithm.
PythonAI Medical
AI medical image analysis, in the early identification of cancer, artificial intelligence on the film recognition ability, has also surpassed human doctors.
There are so many fun and useful things Python can do! Welcome to share and discuss with us
Fun things to do with Python users. Look forward to more fun things you can do with Python!