程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

7 practical Python automation code, stop building wheels

編輯:Python

About Python There is a famous saying : Don't make wheels over and over again .

But there are three problems :

1、 You don't know which wheels have been built , Which one suits you . Famous wheels with names and surnames are 400 Multiple , Not to mention no name, no surname, their own wheels in production .

2、 It's true that there's no duplication of wheels , But making cars over and over again . Including hundreds of lines of code written by many gods , The solution is Excel It has its own mature functions .

3、 A lot of people use it to capture pictures , data , Grab some pictures 、 video 、 Have fun with the weather forecast , so what ? What's the use of big data ? For example, XX beer sells fast , so what ? For example, the box office of so and so is high , so what ?

Here's what happened Python3.6.4 Debug passed code , Share with you :

  • 1、 Grab Zhihu pictures
  • 2、 Listen to two chat robots talking to each other
  • 3、AI The author of Tang poetry is Li Bai or Du Fu
  • 4、 Lottery tickets are randomly generated 35 choose 7
  • 5、 Automatic writing of review
  • 6、 Screen recorders
  • 7、 Make Gif Moving graph

Capture Zhihu pictures only 30 Line code

from selenium import webdriver
import time
import urllib.request
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.zhihu.com/question/29134042")
i = 0
while i < 10:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
try:
driver.find_element_by_css_selector('button.QuestionMainAction').click()
print("page" + str(i))
time.sleep(1)
except:
break
result_raw = driver.page_source
content_list = re.findall("img src=\"(.+?)\" ", str(result_raw))
n = 0
while n < len(content_list):
i = time.time()
local = (r"%s.jpg" % (i))
urllib.request.urlretrieve(content_list[n], local)
print(" Number :" + str(i))
n = n + 1

When you're free, listen to two chat robots chat with each other

from time import sleep
import requests
s = input(" Please input the topic :")
while True:
resp = requests.post("http://www.tuling123.com/openapi/api",data={"key":"4fede3c4384846b9a7d0456a5e1e2943", "info": s, })
resp = resp.json()
sleep(1)
print(' Little fish :', resp['text'])
s = resp['text']
resp = requests.get("http://api.qingyunke.com/api.php", {'key': 'free', 'appid':0, 'msg': s})
resp.encoding = 'utf8'
resp = resp.json()
sleep(1)
print(' Fifi :', resp['content'])
# There is also a little girl on the Internet who is said to have a high IQ i robot , Use the function of crawler to realize :
import urllib.request
import re
while True:
x = input(" master :")
x = urllib.parse.quote(x)
link = urllib.request.urlopen(
"http://nlp.xiaoi.com/robot/webrobot?&callback=__webrobot_processMsg&data=%7B%22sessionId%22%3A%22ff725c236e5245a3ac825b2dd88a7501%22%2C%22robotId%22%3A%22webbot%22%2C%22userId%22%3A%227cd29df3450745fbbdcf1a462e6c58e6%22%2C%22body%22%3A%7B%22content%22%3A%22" + x + "%22%7D%2C%22type%22%3A%22txt%22%7D")
html_doc = link.read().decode()
reply_list = re.findall(r'\"content\":\"(.+?)\\r\\n\"', html_doc)
print(" Small i:" + reply_list[-1])

The author of Tang poetry is Li Bai or Du Fu

import jieba
from nltk.classify import NaiveBayesClassifier
# We need to collect Li Bai's poems in advance , Put it in libai.txt In the text .
text1 = open(r"libai.txt", "rb").read()
list1 = jieba.cut(text1)
result1 = " ".join(list1)
# We need to collect Du Fu's poems in advance , Put it in dufu.txt In the text .
text2 = open(r"dufu.txt", "rb").read()
list2 = jieba.cut(text2)
result2 = " ".join(list2)
# Data preparation
libai = result1
dufu = result2
# feature extraction
def word_feats(words):
return dict([(word, True) for word in words])
libai_features = [(word_feats(lb), 'lb') for lb in libai]
dufu_features = [(word_feats(df), 'df') for df in dufu]
train_set = libai_features + dufu_features
# Training decisions
classifier = NaiveBayesClassifier.train(train_set)
# Analysis test
sentence = input(" Please input a poem you like :")
print("\n")
seg_list = jieba.cut(sentence)
result1 = " ".join(seg_list)
words = result1.split(" ")
# The statistical results
lb = 0
df = 0
for word in words:
classResult = classifier.classify(word_feats(word))
if classResult == 'lb':
lb = lb + 1
if classResult == 'df':
df = df + 1
# The proportion
x = float(str(float(lb) / len(words)))
y = float(str(float(df) / len(words)))
print(' The possibility of Li Bai :%.2f%%' % (x * 100))
print(' The possibility of Du Fu :%.2f%%' % (y * 100))

Lottery tickets are randomly generated 35 choose 7

import random
temp = [i + 1 for i in range(35)]
random.shuffle(temp)
i = 0
list = []
while i < 7:
list.append(temp[i])
i = i + 1
list.sort()
print('\033[0;31;;1m')
print(*list[0:6], end="")
print('\033[0;34;;1m', end=" ")
print(list[-1])

Automatic writing of review

import random
import xlrd
ExcelFile = xlrd.open_workbook(r'test.xlsx')
sheet = ExcelFile.sheet_by_name('Sheet1')
i = []
x = input(" Please enter the specific event :")
y = int(input(" The number of words required by the teacher :"))
while len(str(i)) < y * 1.2:
s = random.randint(1, 60)
rows = sheet.row_values(s)
i.append(*rows)
print(" "*8+" Self - criticism Text "+"\n"+" teacher :")
print(" I shouldn't have " + str(x)+",", *i)
print(" Please forgive me again !")
'''
Here's a sample :
Please enter the specific event : smoking
The number of words required by the teacher :200
Self - criticism Text
teacher :
I shouldn't smoke , As soon as the school starts, it makes repeated orders , Repeatedly stressed the school rules and discipline , Remind students not to violate school rules , But I didn't pay attention to what the school and teachers said , I didn't pay attention to what the teacher said , Not paying attention to the important issues issued by the school , It's like a deaf ear , These are not supposed to be . At the same time, I sincerely hope that teachers can continue to care and support me , And I'll take care of my problems . No matter in the study or in other aspects, I will use the school rules to be strict with myself , I'll take this opportunity . But it turns out , Just passion 、 Work hard 、 Studying is not enough , And have a clear political mind 、 Sense of overall situation and sense of discipline , Otherwise, you will lose your way in learning , The loss of the state and the school .
Please forgive me again !
'''

Screen capture software of screen recorder

from time import sleep
from PIL import ImageGrab
m = int(input(" Please enter the number of minutes you want to capture the screen :"))
m = m * 60
n = 1
while n < m:
sleep(0.02)
im = ImageGrab.grab()
local = (r"%s.jpg" % (n))
im.save(local, 'jpeg')
n = n + 1

Make Gif Moving graph

from PIL import Image
im = Image.open("1.jpg")
images = []
images.append(Image.open('2.jpg'))
images.append(Image.open('3.jpg'))
im.save('gif.gif', save_all=True, append_images=images, loop=1, duration=1, comment=b"aaabb")

Learning resource sharing

Finally, thank everyone who reads my article carefully , Watching the rise and attention of fans all the way , Reciprocity is always necessary , Although it's not very valuable , If you can use it, you can take it

These materials , For 【 software test 】 For our friends, it should be the most comprehensive and complete war preparation warehouse , This warehouse also accompanied me through the most difficult journey , I hope it can help you ! Everything should be done as soon as possible , Especially in the technology industry , We must improve our technical skills . I hope that's helpful …….


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved