<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          7個實用的Python自動化代碼,別再重復造輪子了!

          共 7433字,需瀏覽 15分鐘

           ·

          2022-04-26 07:31


          關于Python有一句名言:不要重復造輪子。


          但是問題有三個:


          1、你不知道已經有哪些輪子已經造好了,哪個適合你用。有名有姓的的著名輪子就400多個,更別說沒名沒姓自己在制造中的輪子。


          2、確實沒重復造輪子,但是在重復制造汽車。包括好多大神寫的好幾百行代碼,為的是解決一個Excel本身就有的成熟功能。


          3、很多人是用來抓圖,數(shù)據,抓點圖片、視頻、天氣預報自娛自樂一下,然后呢?抓到大數(shù)據以后做什么用呢?比如某某啤酒賣的快,然后呢?比如某某電影票房多,然后呢?


          以下是經過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 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機器人,用爬蟲的功能來實現(xiàn)一下:

          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)

          # 數(shù)據準備
          libai = result1
          dufu = result2


          # 特征提取
          def word_feats(words):
              return dict([(word, Truefor 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(" ")

          # 統(tǒng)計結果


          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

          # 呈現(xiàn)比例
          x = float(str(float(lb) / len(words)))
          y = float(str(float(df) / len(words)))
          print('李白的可能性:%.2f%%' % (x * 100))
          print('杜甫的可能性:%.2f%%' % (y * 100))



          ④ 彩票隨機生成35選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])



          ⑤ 自動寫檢討書


          import random
          import xlrd

          ExcelFile = xlrd.open_workbook(r'test.xlsx')
          sheet = ExcelFile.sheet_by_name('Sheet1')
          i = []
          x = input("請輸入具體事件:")
          y = int(input("老師要求的字數(shù):"))
          while len(str(i)) < y * 1.2:
              s = random.randint(160)
              rows = sheet.row_values(s)
              i.append(*rows)
          print(" "*8+"檢討書"+"\n"+"老師:")
          print("我不應該" + str(x)+",", *i)
          print("再次請老師原諒!")
          '''
          以下是樣稿:

          請輸入具體事件:抽煙
          老師要求的字數(shù):200
                  檢討書
          老師:
          我不應該抽煙, 學校一開學就三令五申,一再強調校規(guī)校紀,提醒學生不要違反校規(guī),可我卻沒有把學校和老師的話放在心上,沒有重視老師說的話,沒有重視學校頒布的重要事項,當成了耳旁風,這些都是不應該的。同時也真誠地希望老師能繼續(xù)關心和支持我,并卻對我的問題酌情處理。 無論在學習還是在別的方面我都會用校規(guī)來嚴格要求自己,我會把握這次機會。 但事實證明,僅僅是熱情投入、刻苦努力、鉆研學業(yè)是不夠的,還要有清醒的政治頭腦、大局意識和紀律觀念,否則就會在學習上迷失方向,使國家和學校受損失。
          再次請老師原諒!
          '''



          ⑥ 屏幕錄相機,抓屏軟件


          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 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")


          --- EOF ---
          程序員技術交流群
          隨著讀者越來越多,我也建了幾個技術交流群,九分聊技術,一分聊風雪,歡迎有興趣的同學加入我們。
          可以長按識別下方二維碼,一定要注意:城市+昵稱+Python,根據格式,可以更快捷地通過選擇內容進入群。

          ▲長按掃描


           閱讀更多


          1. python爬蟲:爬取男生喜歡的圖片
          2. Python 偷偷爬取QQ音樂全部歌曲
          3. Python破解VIP視頻 (免費看VIP視頻)

          人生苦短,我用python


          神秘禮包獲取方式

          識別文末二維碼,回復:Python
           

          覺得不錯,點個“在看”然后轉發(fā)出去

          瀏覽 43
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  免费亚洲免费 | 亚洲欧美V| 又粗又大操逼视频 | 99在线观看精品视频 | 天天肏天天射 |