七個實用的Python自動化程式碼,別再重複造輪子了!
關於Python有一句名言:不要重複造輪子。
但是問題有三個:
1、你不知道已經有哪些輪子已經造好了,哪個適合你用。有名有姓的著名輪子的就400多個,更別說沒名沒姓自己在製造中的輪子。
2、確實沒重複造輪子,但在重複製造汽車。包含好多大神寫的好幾百行程式碼,為的是解決一個Excel本身就有的成熟功能。
3、很多人是用來抓圖,數據,抓點圖片、影片、天氣預報自娛自樂一下,然後呢?抓到大數據以後做什麼用?例如某某啤酒賣的快,然後呢?例如某某電影票房多,然後呢?
以下是經過Python3.6.4調試通過的程式碼,與大家分享:
#1、抓取知乎圖片
2、聽兩個聊天機器人互相聊天
3、AI分析唐詩的作者是李白還是杜甫
4、彩券隨機產生35選7
#5、自動寫檢討書
##6、螢幕錄相機7、製作Gif動圖① 抓取知乎圖片,只用30行代碼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("编号:" + str(i))
n = n + 1
登入後複製
② 沒事閒的時候,聽兩個聊天機器人互相聊天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("编号:" + str(i)) n = n + 1
from time import sleep
import requests
s = input("请主人输入话题:")
while True:
resp = requests.post("http://www.tuling123.com/openapi/api",data={"key":"4fede3c4384846b9a7d0456a5e1e2943", "info": s, })
resp = resp.json()
sleep(1)
print('小鱼:', 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('菲菲:', resp['content'])
#网上还有一个据说智商比较高的小i机器人,用爬虫的功能来实现一下:
import urllib.request
import re
while True:
x = input("主人:")
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("小i:" + reply_list[-1])
登入後複製
③ 分析唐詩的作者是李白還是杜甫from time import sleep import requests s = input("请主人输入话题:") while True: resp = requests.post("http://www.tuling123.com/openapi/api",data={"key":"4fede3c4384846b9a7d0456a5e1e2943", "info": s, }) resp = resp.json() sleep(1) print('小鱼:', 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('菲菲:', resp['content']) #网上还有一个据说智商比较高的小i机器人,用爬虫的功能来实现一下: import urllib.request import re while True: x = input("主人:") 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("小i:" + reply_list[-1])
import jieba
from nltk.classify import NaiveBayesClassifier
# 需要提前把李白的诗收集一下,放在libai.txt文本中。
text1 = open(r"libai.txt", "rb").read()
list1 = jieba.cut(text1)
result1 = " ".join(list1)
# 需要提前把杜甫的诗收集一下,放在dufu.txt文本中。
text2 = open(r"dufu.txt", "rb").read()
list2 = jieba.cut(text2)
result2 = " ".join(list2)
# 数据准备
libai = result1
dufu = result2
# 特征提取
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
# 训练决策
classifier = NaiveBayesClassifier.train(train_set)
# 分析测试
sentence = input("请输入一句你喜欢的诗:")
print("n")
seg_list = jieba.cut(sentence)
result1 = " ".join(seg_list)
words = result1.split(" ")
# 统计结果
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
# 呈现比例
x = float(str(float(lb) / len(words)))
y = float(str(float(df) / len(words)))
print('李白的可能性:%.2f%%' % (x * 100))
print('杜甫的可能性:%.2f%%' % (y * 100))
登入後複製
④ 彩票隨機產生35選7import jieba from nltk.classify import NaiveBayesClassifier # 需要提前把李白的诗收集一下,放在libai.txt文本中。 text1 = open(r"libai.txt", "rb").read() list1 = jieba.cut(text1) result1 = " ".join(list1) # 需要提前把杜甫的诗收集一下,放在dufu.txt文本中。 text2 = open(r"dufu.txt", "rb").read() list2 = jieba.cut(text2) result2 = " ".join(list2) # 数据准备 libai = result1 dufu = result2 # 特征提取 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 # 训练决策 classifier = NaiveBayesClassifier.train(train_set) # 分析测试 sentence = input("请输入一句你喜欢的诗:") print("n") seg_list = jieba.cut(sentence) result1 = " ".join(seg_list) words = result1.split(" ") # 统计结果 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 # 呈现比例 x = float(str(float(lb) / len(words))) y = float(str(float(df) / len(words))) print('李白的可能性:%.2f%%' % (x * 100)) print('杜甫的可能性:%.2f%%' % (y * 100))
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('33[0;31;;1m')
print(*list[0:6], end="")
print('33[0;34;;1m', end=" ")
print(list[-1])
登入後複製
⑤ 自動寫檢討書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('33[0;31;;1m') print(*list[0:6], end="") print('33[0;34;;1m', end=" ") print(list[-1])
import random
import xlrd
ExcelFile = xlrd.open_workbook(r'test.xlsx')
sheet = ExcelFile.sheet_by_name('Sheet1')
i = []
x = input("请输入具体事件:")
y = int(input("老师要求的字数:"))
while len(str(i)) < y * 1.2:
s = random.randint(1, 60)
rows = sheet.row_values(s)
i.append(*rows)
print(" "*8+"检讨书"+"n"+"老师:")
print("我不应该" + str(x)+",", *i)
print("再次请老师原谅!")
'''
以下是样稿:
请输入具体事件:抽烟
老师要求的字数:200
检讨书
老师:
我不应该抽烟, 学校一开学就三令五申,一再强调校规校纪,提醒学生不要违反校规,可我却没有把学校和老师的话放在心上,没有重视老师说的话,没有重视学校颁布的重要事项,当成了耳旁风,这些都是不应该的。同时也真诚地希望老师能继续关心和支持我,并却对我的问题酌情处理。 无论在学习还是在别的方面我都会用校规来严格要求自己,我会把握这次机会。 但事实证明,仅仅是热情投入、刻苦努力、钻研学业是不够的,还要有清醒的政治头脑、大局意识和纪律观念,否则就会在学习上迷失方向,使国家和学校受损失。
再次请老师原谅!
'''
登入後複製
⑥ 螢幕錄相機,抓取軟體import random import xlrd ExcelFile = xlrd.open_workbook(r'test.xlsx') sheet = ExcelFile.sheet_by_name('Sheet1') i = [] x = input("请输入具体事件:") y = int(input("老师要求的字数:")) while len(str(i)) < y * 1.2: s = random.randint(1, 60) rows = sheet.row_values(s) i.append(*rows) print(" "*8+"检讨书"+"n"+"老师:") print("我不应该" + str(x)+",", *i) print("再次请老师原谅!") ''' 以下是样稿: 请输入具体事件:抽烟 老师要求的字数:200 检讨书 老师: 我不应该抽烟, 学校一开学就三令五申,一再强调校规校纪,提醒学生不要违反校规,可我却没有把学校和老师的话放在心上,没有重视老师说的话,没有重视学校颁布的重要事项,当成了耳旁风,这些都是不应该的。同时也真诚地希望老师能继续关心和支持我,并却对我的问题酌情处理。 无论在学习还是在别的方面我都会用校规来严格要求自己,我会把握这次机会。 但事实证明,仅仅是热情投入、刻苦努力、钻研学业是不够的,还要有清醒的政治头脑、大局意识和纪律观念,否则就会在学习上迷失方向,使国家和学校受损失。 再次请老师原谅! '''
from time import sleep
from PIL import ImageGrab
m = int(input("请输入想抓屏几分钟:"))
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
登入後複製
⑦ 製作Gif動圖from time import sleep from PIL import ImageGrab m = int(input("请输入想抓屏几分钟:")) 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
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")
登入後複製
可以試著玩起來了。 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")
以上是七個實用的Python自動化程式碼,別再重複造輪子了!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

在 Sublime Text 中運行 Python 代碼,需先安裝 Python 插件,再創建 .py 文件並編寫代碼,最後按 Ctrl B 運行代碼,輸出會在控制台中顯示。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

在 Visual Studio Code(VSCode)中編寫代碼簡單易行,只需安裝 VSCode、創建項目、選擇語言、創建文件、編寫代碼、保存並運行即可。 VSCode 的優點包括跨平台、免費開源、強大功能、擴展豐富,以及輕量快速。

在 Notepad 中運行 Python 代碼需要安裝 Python 可執行文件和 NppExec 插件。安裝 Python 並為其添加 PATH 後,在 NppExec 插件中配置命令為“python”、參數為“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通過快捷鍵“F6”運行 Python 代碼。
