2024年最新25 个很棒的 Python 脚本合集(迷你项目) - PDF 下载(1),一个APP从启动到主页面显示经历了哪些过程

如果你也是看准了Python,想自学Python,在这里为大家准备了丰厚的免费学习大礼包,带大家一起学习,给大家剖析Python兼职、就业行情前景的这些事儿。

一、Python所有方向的学习路线

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

二、学习软件

工欲善其必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。

三、全套PDF电子书

书籍的好处就在于权威和体系健全,刚开始学习的时候你可以只看视频或者听某个人讲课,但等你学完之后,你觉得你掌握了,这时候建议还是得去看一下书籍,看权威技术书籍也是每个程序员必经之路。

四、入门学习视频

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。

四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

五、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

成为一个Python程序员专家或许需要花费数年时间,但是打下坚实的基础只要几周就可以,如果你按照我提供的学习路线以及资料有意识地去实践,你就有很大可能成功!
最后祝你好运!!!

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

# terminating the session s.quit() print("sent")

if __name__ == "__main__": send_mail()

11.获取网站的IP地址和主机名


Get Ipaddress and Hostname of Website# importing socket libraryimport socket`

def get_hostname_IP(): hostname = input("Please enter website address(URL):") try: print (f'Hostname: {hostname}') print (f'IP: {socket.gethostbyname(hostname)}') except socket.gaierror as error: print (f'Invalid Hostname, error raised is {error}')

`get_hostname_IP()

12.终端进度条


from tqdm import tqdm``from PIL import Image``import os``from time import sleep

def Resize_image(size, image): if os.path.isfile(image): try: im = Image.open(image) im.thumbnail(size, Image.ANTIALIAS) im.save("resize/" + str(image) + ".jpg") except Exception as ex: print(f"Error: {str(ex)} to {image}")

path = input("Enter Path to images : ")``size = input("Size Height , Width : ")``size = tuple(map(int, size.split(",")))

os.chdir(path)

list_images = os.listdir(path)``if "resize" not in list_images: os.mkdir("resize")

for image in tqdm(list_images, desc="Resizing Images"): Resize_image(size, image) sleep(0.1)``print("Resizing Completed!")

13. Wifi密码弹出器


import subprocess`

data = ( subprocess.check_output(["netsh", "wlan", "show", "profiles"]) .decode("utf-8") .split("\n")``)``profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]``for i in profiles: results = ( subprocess .check_output(["netsh", "wlan", "show", "profile", i, "key=clear"]) .decode("utf-8") .split("\n") ) results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b] try: print("{:<30}| {:<}".format(i, results[0])) except IndexError: `print(“{:<30}| {:<}”.format(i, “”))

14.给定网站的快照


import sysfrom selenium import webdriverfrom selenium.webdriver.chrome.options import Options``import chromedriver_binary`

script_name = sys.argv[0]

options = Options()``options.add_argument('--headless')``driver = webdriver.Chrome(options=options)

try: url = sys.argv[1]

driver.get(url) page_width = driver.execute_script('return document.body.scrollWidth') page_height = driver.execute_script('return document.body.scrollHeight') driver.set_window_size(page_width, page_height) driver.save_screenshot('screenshot.png') driver.quit() print("SUCCESS")

except IndexError: `print(‘Usage: %s URL’ % script_name)

15.将文件拆分成块​​​​​​​


import sysimport osimport shutil``import pandas as pd`

class Split_Files: ''' Class file for split file program ''' def __init__(self, filename, split_number): ''' Getting the file name and the split index Initializing the output directory, if present then truncate it. Getting the file extension ''' self.file_name = filename self.directory = "file_split" self.split = int(split_number) if os.path.exists(self.directory): shutil.rmtree(self.directory) os.mkdir(self.directory) if self.file_name.endswith('.txt'): self.file_extension = '.txt' else: self.file_extension = '.csv' self.file_number = 1

def split_data(self): ''' spliting the input csv/txt file according to the index provided ''' data = pd.read_csv(self.file_name, header=None) data.index += 1

split_frame = pd.DataFrame() output_file = f"{self.directory}/split_file{self.file_number}{self.file_extension}"

for i in range(1, len(data)+1): split_frame = split_frame.append(data.iloc[i-1]) if i % self.split == 0: output_file = f"{self.directory}/split_file{self.file_number}{self.file_extension}" if self.file_extension == '.txt': split_frame.to_csv(output_file, header=False, index=False, sep=' ') else: split_frame.to_csv(output_file, header=False, index=False) split_frame.drop(split_frame.index, inplace=True) self.file_number += 1 if not split_frame.empty: output_file = f"{self.directory}/split_file{self.file_number}{self.file_extension}" split_frame.to_csv(output_file, header=False, index=False)

if __name__ == '__main__': file, split_number = sys.argv[1], sys.argv[2] sp = Split_Files(file, split_number) `sp.split_data()

16.加密和解密文本


​​​​​​​

from Crypto.Cipher import AESfrom Crypto import Randomfrom binascii import b2a_hex``import sys`

# get the plaintext``plain_text = sys.argv[1]

# The key length must be 16 (AES-128), 24 (AES-192), or 32 (AES-256) Bytes.``key = b'this is a 16 key'

# Generate a non-repeatable key vector with a length``# equal to the size of the AES block``iv = Random.new().read(AES.block_size)

# Use key and iv to initialize AES object, use MODE_CFB mode``mycipher = AES.new(key, AES.MODE_CFB, iv)

# Add iv (key vector) to the beginning of the encrypted ciphertext``# and transmit it together``ciphertext = iv + mycipher.encrypt(plain_text.encode())

# To decrypt, use key and iv to generate a new AES object``mydecrypt = AES.new(key, AES.MODE_CFB, ciphertext[:16])

# Use the newly generated AES object to decrypt the encrypted ciphertext``decrypttext = mydecrypt.decrypt(ciphertext[16:])

# output``file_out = open("encrypted.bin", "wb")``file_out.write(ciphertext[16:])``file_out.close()

`print("The key k is: ", key)print("iv is: ", b2a_hex(ciphertext)[:16])print("The encrypted data is: ", b2a_hex(ciphertext)[16:])``print("The decrypted data is: ", decrypttext.decode())

17.定期截屏


​​​​​​​

import osimport argparseimport pyautogui``import time`

parser = argparse.ArgumentParser()

parser.add_argument("-p", "--path", help="absolute path to store screenshot.", default=r"./images")``parser.add_argument("-t", "--type", help="h (in hour) or m (in minutes) or s (in seconds)", default='h')``parser.add_argument("-f", "--frequency", help="frequency for taking screenshot per h/m/s.", default=1, type=int)

args = parser.parse_args()

sec = 0.

if args.type == 'h': sec = 60 * 60 / args.frequency``elif args.type == 'm': sec = 60 / args.frequency

if sec < 1.: sec = 1.

if os.path.isdir(args.path) != True: os.mkdir(args.path)

try: while True: t = time.localtime() current_time = time.strftime("%H_%M_%S", t) file = current_time + ".jpg" image = pyautogui.screenshot(os.path.join(args.path,file)) print(f"{file} saved successfully.\n") time.sleep(sec)

except KeyboardInterrupt: `print(“End of script by user interrupt”)

18.十进制到二进制转换器


​​​​​​​

try: menu = int(input("Choose an option: \n 1. Decimal to binary \n 2. Binary to decimal\n Option: ")) if menu < 1 or menu > 2: raise ValueError if menu == 1: dec = int(input("Input your decimal number:\nDecimal: ")) print(“Binary: {}”.format(bin(dec)[2:])) elif menu == 2: binary = input("Input your binary number:\n Binary: ") print(“Decimal: {}”.format(int(binary, 2)))``except ValueError: print (“please choose a valid option”)

19. CLI 待办事项应用程序


​​​​​​​

​​​​​​​

import click`

')[0]:en.split('

@todo.command()``@click.pass_context``def tasks(ctx): '''Display tasks''' if ctx.obj['TASKS']: click.echo('YOUR TASKS\n**********') #Iterate through all the tasks stored in the context for i, task in ctx.obj['TASKS'].items(): click.echo('• ' + task + ' (ID: ' + i + ')') click.echo('') else: click.echo('No tasks yet! Use ADD to add one.\n')

if __name__ == '__main__': `todo()

20.货币转换器


import requests import jsonimport sysfrom pprint import pprint`

# The below 4 lines bring out the value of currency from the api at fixer.io. I had to register there, the key is unique to me.``url = "http://data.fixer.io/api/latest?access_key=33ec7c73f8a4eb6b9b5b5f95118b2275"``data = requests.get(url).text``data2 = json.loads(data) #brings whether request was successful,timestamp etc``fx = data2["rates"]

currencies = [ "AED : Emirati Dirham,United Arab Emirates Dirham", "AFN : Afghan Afghani,Afghanistan Afghani", "ALL : Albanian Lek,Albania Lek", "AMD : Armenian Dram,Armenia Dram", "ANG : Dutch Guilder,Netherlands Antilles Guilder,Bonaire,Cura&#231;ao,Saba,Sint Eustatius,Sint Maarten", "AOA : Angolan Kwanza,Angola Kwanza", "ARS : Argentine Peso,Argentina Peso,Islas Malvinas", "AUD : Australian Dollar,Australia Dollar,Christmas Island,Cocos (Keeling) Islands,Norfolk Island,Ashmore and Cartier Islands,Australian Antarctic Territory,Coral Sea Islands,Heard Island,McDonald Islands,Kiribati,Nauru", "AWG : Aruban or Dutch Guilder,Aruba Guilder", "AZN : Azerbaijan Manat,Azerbaijan Manat", "BAM : Bosnian Convertible Mark,Bosnia and Herzegovina Convertible Mark", "BBD : Barbadian or Bajan Dollar,Barbados Dollar", "BDT : Bangladeshi Taka,Bangladesh Taka", "BGN : Bulgarian Lev,Bulgaria Lev", "BHD : Bahraini Dinar,Bahrain Dinar", "BIF : Burundian Franc,Burundi Franc", "BMD : Bermudian Dollar,Bermuda Dollar", "BND : Bruneian Dollar,Brunei Darussalam Dollar", "BOB : Bolivian Bol&#237;viano,Bolivia Bol&#237;viano", "BRL : Brazilian Real,Brazil Real", "BSD : Bahamian Dollar,Bahamas Dollar", "BTC : Bitcoin,BTC, XBT", "BTN : Bhutanese Ngultrum,Bhutan Ngultrum", "BWP : Botswana Pula,Botswana Pula", "BYN : Belarusian Ruble,Belarus Ruble", "BYR : Belarusian Ruble,Belarus Ruble", "BZD : Belizean Dollar,Belize Dollar", "CAD : Canadian Dollar,Canada Dollar", "CDF : Congolese Franc,Congo/Kinshasa Franc", "CHF : Swiss Franc,Switzerland Franc,Liechtenstein,Campione d&#039;Italia,B&#252;singen am Hochrhein", "CLF : Chilean Unit of Account", "CLP : Chilean Peso,Chile Peso", "CNY : Chinese Yuan Renminbi,China Yuan Renminbi", "COP : Colombian Peso,Colombia Peso", "CRC : Costa Rican Colon,Costa Rica Colon", "CUC : Cuban Convertible Peso,Cuba Convertible Peso", "CUP : Cuban Peso,Cuba Peso", "CVE : Cape Verdean Escudo,Cape Verde Escudo", "CZK : Czech Koruna,Czech Republic Koruna", "DJF : Djiboutian Franc,Djibouti Franc", "DKK : Danish Krone,Denmark Krone,Faroe Islands,Greenland", "DOP : Dominican Peso,Dominican Republic Peso", "DZD : Algerian Dinar,Algeria Dinar", "EGP : Egyptian Pound,Egypt Pound,Gaza Strip", "ERN : Eritrean Nakfa,Eritrea Nakfa", "ETB : Ethiopian Birr,Ethiopia Birr,Eritrea", "EUR : Euro,Euro Member Countries,Andorra,Austria,Azores,Baleares (Balearic Islands),Belgium,Canary Islands,Cyprus,Finland,France,French Guiana,French Southern Territories,Germany,Greece,Guadeloupe,Holland (Netherlands),Holy See (Vatican City),Ireland (Eire),Italy,Luxembourg,Madeira Islands,Malta,Monaco,Montenegro,Netherlands", "FJD : Fijian Dollar,Fiji Dollar", "FKP : Falkland Island Pound,Falkland Islands (Malvinas) Pound", "GBP : British Pound,United Kingdom Pound,United Kingdom (UK),England,Northern Ireland,Scotland,Wales,Falkland Islands,Gibraltar,Guernsey,Isle of Man,Jersey,Saint Helena and Ascension,South Georgia and the South Sandwich Islands,Tristan da Cunha", "GEL : Georgian Lari,Georgia Lari", "GGP : Guernsey Pound,Guernsey Pound", "GHS : Ghanaian Cedi,Ghana Cedi", "GIP : Gibraltar Pound,Gibraltar Pound", "GMD : Gambian Dalasi,Gambia Dalasi", "GNF : Guinean Franc,Guinea Franc", "GTQ : Guatemalan Quetzal,Guatemala Quetzal", "GYD : Guyanese Dollar,Guyana Dollar", "HKD : Hong Kong Dollar,Hong Kong Dollar", "HNL : Honduran Lempira,Honduras Lempira", "HRK : Croatian Kuna,Croatia Kuna", "HTG : Haitian Gourde,Haiti Gourde", "HUF : Hungarian Forint,Hungary Forint", "IDR : Indonesian Rupiah,Indonesia Rupiah,East Timor", "ILS : Israeli Shekel,Israel Shekel,Palestinian Territories", "IMP : Isle of Man Pound,Isle of Man Pound", "INR : Indian Rupee,India Rupee,Bhutan,Nepal", "IQD : Iraqi Dinar,Iraq Dinar", "IRR : Iranian Rial,Iran Rial", "ISK : Icelandic Krona,Iceland Krona", "JEP : Jersey Pound,Jersey Pound", "JMD : Jamaican Dollar,Jamaica Dollar", "JOD : Jordanian Dinar,Jordan Dinar", "JPY : Japanese Yen,Japan Yen", "KES : Kenyan Shilling,Kenya Shilling", "KGS : Kyrgyzstani Som,Kyrgyzstan Som", "KHR : Cambodian Riel,Cambodia Riel", "KMF : Comorian Franc,Comorian Franc", "KPW : North Korean Won,Korea (North) Won", "KRW : South Korean Won,Korea (South) Won", "KWD : Kuwaiti Dinar,Kuwait Dinar", "KYD : Caymanian Dollar,Cayman Islands Dollar", "KZT : Kazakhstani Tenge,Kazakhstan Tenge", "LAK : Lao Kip,Laos Kip", "LBP : Lebanese Pound,Lebanon Pound", "LKR : Sri Lankan Rupee,Sri Lanka Rupee", "LRD : Liberian Dollar,Liberia Dollar", "LSL : Basotho Loti,Lesotho Loti", "LTL : Lithuanian litas", "LVL : Latvia Lats", "LYD : Libyan Dinar,Libya Dinar", "MAD : Moroccan Dirham,Morocco Dirham,Western Sahara", "MDL : Moldovan Leu,Moldova Leu", "MGA : Malagasy Ariary,Madagascar Ariary", "MKD : Macedonian Denar,Macedonia Denar", "MMK : Burmese Kyat,Myanmar (Burma) Kyat", "MNT : Mongolian Tughrik,Mongolia Tughrik", "MOP : Macau Pataca,Macau Pataca", "MRU : Mauritanian Ouguiya,Mauritania Ouguiya", "MUR : Mauritian Rupee,Mauritius Rupee", "MVR : Maldivian Rufiyaa,Maldives (Maldive Islands) Rufiyaa", "MWK : Malawian Kwacha,Malawi Kwacha", "MXN : Mexican Peso,Mexico Peso", "MYR : Malaysian Ringgit,Malaysia Ringgit", "MZN : Mozambican Metical,Mozambique Metical", "NAD : Namibian Dollar,Namibia Dollar", "NGN : Nigerian Naira,Nigeria Naira", "NIO : Nicaraguan Cordoba,Nicaragua Cordoba", "NOK : Norwegian Krone,Norway Krone,Bouvet Island,Svalbard,Jan Mayen,Queen Maud Land,Peter I Island", "NPR : Nepalese Rupee,Nepal Rupee,India (unofficially near India-Nepal border)", "NZD : New Zealand Dollar,New Zealand Dollar,Cook Islands,Niue,Pitcairn Islands,Tokelau", "OMR : Omani Rial,Oman Rial", "PAB : Panamanian Balboa,Panama Balboa", "PEN : Peruvian Sol,Peru Sol", "PGK : Papua New Guinean Kina,Papua New Guinea Kina", "PHP : Philippine Peso,Philippines Peso", "PKR : Pakistani Rupee,Pakistan Rupee", "PLN : Polish Zloty,Poland Zloty", "PYG : Paraguayan Guarani,Paraguay Guarani", "QAR : Qatari Riyal,Qatar Riyal", "RON : Romanian Leu,Romania Leu", "RSD : Serbian Dinar,Serbia Dinar", "RUB : Russian Ruble,Russia Ruble,Tajikistan,Abkhazia,South Ossetia", "RWF : Rwandan Franc,Rwanda Franc", "SAR : Saudi Arabian Riyal,Saudi Arabia Riyal", "SBD : Solomon Islander Dollar,Solomon Islands Dollar", "SCR : Seychellois Rupee,Seychelles Rupee", "SDG : Sudanese Pound,Sudan Pound", "SEK : Swedish Krona,Sweden Krona", "SGD : Singapore Dollar,Singapore Dollar", "SHP : Saint Helenian Pound,Saint Helena Pound", "SLL : Sierra Leonean Leone,Sierra Leone Leone", "SOS : Somali Shilling,Somalia Shilling", "SRD : Surinamese Dollar,Suriname Dollar", "STN : Sao Tomean Dobra,S&#227;o Tom&#233; and Pr&#237;ncipe Dobra", "SVC : Salvadoran Colon,El Salvador Colon", "SYP : Syrian Pound,Syria Pound", "SZL : Swazi Lilangeni,eSwatini Lilangeni", "THB : Thai Baht,Thailand Baht", "TJS : Tajikistani Somoni,Tajikistan Somoni", "TMT : Turkmenistani Manat,Turkmenistan Manat", "TND : Tunisian Dinar,Tunisia Dinar", "TOP : Tongan Pa&#039;anga,Tonga Pa&#039;anga", "TRY : Turkish Lira,Turkey Lira,North Cyprus", "TTD : Trinidadian Dollar,Trinidad and Tobago Dollar,Trinidad,Tobago", "TWD : Taiwan New Dollar,Taiwan New Dollar", "TZS : Tanzanian Shilling,Tanzania Shilling", "UAH : Ukrainian Hryvnia,Ukraine Hryvnia", "UGX : Ugandan Shilling,Uganda Shilling", "USD : US Dollar,United States Dollar,America,American Samoa,American Virgin Islands,British Indian Ocean Territory,British Virgin Islands,Ecuador,El Salvador,Guam,Haiti,Micronesia,Northern Mariana Islands,Palau,Panama,Puerto Rico,Turks and Caicos Islands,United States Minor Outlying Islands,Wake Island,East Timor", "UYU : Uruguayan Peso,Uruguay Peso", "UZS : Uzbekistani Som,Uzbekistan Som", "VEF : Venezuelan Bol&#237;var,Venezuela Bol&#237;var", "VND : Vietnamese Dong,Viet Nam Dong", "VUV : Ni-Vanuatu Vatu,Vanuatu Vatu", "WST : Samoan Tala,Samoa Tala", "XAF : Central African CFA Franc BEAC,Communaut&#233; Financi&#232;re Africaine (BEAC) CFA Franc BEAC,Cameroon,Central African Republic,Chad,Congo/Brazzaville,Equatorial Guinea,Gabon", "XAG : Silver Ounce,Silver", "XAU : Gold Ounce,Gold", "XCD : East Caribbean Dollar,East Caribbean Dollar,Anguilla,Antigua and Barbuda,Dominica,Grenada,The Grenadines and Saint Vincent,Montserrat", "XDR : IMF Special Drawing Rights,International Monetary Fund (IMF) Special Drawing Rights", "XOF : CFA Franc,Communaut&#233; Financi&#232;re Africaine (BCEAO) Franc,Benin,Burkina Faso,Ivory Coast,Guinea-Bissau,Mali,Niger,Senegal,Togo", "XPF : CFP Franc,Comptoirs Fran&#231;ais du Pacifique (CFP) Franc,French Polynesia,New Caledonia,Wallis and Futuna Islands", "YER : Yemeni Rial,Yemen Rial", "ZAR : South African Rand,South Africa Rand,Lesotho,Namibia", "ZMK : Zambian Kwacha,Zambia Kwacha", "ZMW : Zambian Kwacha,Zambia Kwacha", "ZWL : Zimbabwean Dollar,Zimbabwe Dollar",``]

# The below function calculates the actual conversion``def function1(): query = input( "Please specify the amount of currency to convert, from currency, to currency (with space in between).\nPress SHOW to see list of currencies available. \nPress Q to quit. \n" ) if query == "Q": sys.exit() elif query == "SHOW": pprint(currencies) function1() else: qty, fromC, toC = query.split(" ") fromC = fromC.upper() toC = toC.upper() qty = float(round(int(qty), 2)) amount = round(qty * fx[toC] / fx[fromC], 2) print(f"{qty} of currency {fromC} amounts to {amount} of currency {toC} today")

try: function1()``except KeyError: print("You seem to have inputted wrongly, retry!") `function1()

21.创建一个简单的秒表


import tkinter as Tkinterfrom datetime import datetimecounter = 0``running = False`

def counter_label(label): def count(): if running: global counter # To manage the intial delay.`` if counter == 0: display = 'Ready!' else: tt = datetime.utcfromtimestamp(counter) string = tt.strftime('%H:%M:%S') display = string

label['text'] = display

# label.after(arg1, arg2) delays by`` # first argument given in milliseconds `` # and then calls the function given as second argument. `` # Generally like here we need to call the `` # function in which it is present repeatedly. `` # Delays by 1000ms=1 seconds and call count again. `` label.after(1000, count) counter += 1

# Triggering the start of the counter.`` count()

# start function of the stopwatch def Start(label): global running running = True counter_label(label) start['state'] = 'disabled' stop['state'] = 'normal' reset['state'] = 'normal'

# Stop function of the stopwatch def Stop(): global running start['state'] = 'normal' stop['state'] = 'disabled' reset['state'] = 'normal' running = False

# Reset function of the stopwatch def Reset(label): global counter counter = 0 # If reset is pressed after pressing stop.`` if not running: reset['state'] = 'disabled' label['text'] = '00:00:00' # If reset is pressed while the stopwatch is running.`` else: label['text'] = '00:00:00'

root = Tkinter.Tk()``root.title("Stopwatch")

`# Fixing the window size.root.minsize(width=250, height=70)label = Tkinter.Label(root, text=‘Ready!’, fg=‘black’, font=‘Verdana 30 bold’)label.pack()f = Tkinter.Frame(root)start = Tkinter.Button(f, text='Start', width=6, command=lambda: Start(label))stop = Tkinter.Button(f, text=‘Stop’, width=6, state=‘disabled’, command=Stop)reset = Tkinter.Button(f, text='Reset', width=6, state='disabled', command=lambda: Reset(label))f.pack(anchor=‘center’, pady=5)start.pack(side='left')stop.pack(side=‘left’)reset.pack(side='left')root.mainloop()

22. Python脚本压缩文件夹和文件


import zipfileimport sysimport os`

# compress file function``def zip_file(file_path): compress_file = zipfile.ZipFile(file_path + '.zip', 'w') compress_file.write(path, compress_type=zipfile.ZIP_DEFLATED) compress_file.close()

# Declare the function to return all file paths of the particular directory``def retrieve_file_paths(dir_name): # setup file paths variable file_paths = []

# Read all directory, subdirectories and file lists for root, directories, files in os.walk(dir_name): for filename in files: # Create the full file path by using os module. file_path = os.path.join(root, filename) file_paths.append(file_path)

# return all paths return file_paths

def zip_dir(dir_path, file_paths): # write files and folders to a zipfile compress_dir = zipfile.ZipFile(dir_path + '.zip', 'w') with compress_dir: # write each file separately for file in file_paths: compress_dir.write(file)

if __name__ == "__main__": path = sys.argv[1]

if os.path.isdir(path): files_path = retrieve_file_paths(path) # print the list of files to be zipped print('The following list of files will be zipped:') for file_name in files_path: print(file_name) zip_dir(path, files_path) elif os.path.isfile(path): print('The %s will be zipped:' % path) zip_file(path) else: `print(‘a special file(socket,FIFO,device file), please input file or dir’)

23.查找 IMDB 评级


from bs4 import BeautifulSoupimport requestsimport pandas as pd``import os`

# Setting up session``s = requests.session()

# List contaiting all the films for which data has to be scraped from IMDB``films = []

# Lists contaiting web scraped data``names = []``ratings = []``genres = []

# Define path where your films are present # For eg: "/Users/utkarsh/Desktop/films"``path = input("Enter the path where your films are: ")

# Films with extensions``filmswe = os.listdir(path)

for film in filmswe: # Append into my films list (without extensions) films.append(os.path.splitext(film)[0]) # print(os.path.splitext(film)[0])

for line in films: # x = line.split(", ") title = line.lower() # release = x[1] query = "+".join(title.split())`` URL = "https://www.imdb.com/search/title/?title=" + query print(URL) # print(release) try:`` response = s.get(URL)

#getting contect from IMDB Website content = response.content

# print(response.status_code)

soup = BeautifulSoup(response.content, features="html.parser")`` #searching all films containers found containers = soup.find_all("div", class_="lister-item-content") for result in containers: name1 = result.h3.a.text name = result.h3.a.text.lower()

# Uncomment below lines if you want year specific as well, define year variable before this`` # year = result.h3.find( # "span", class_="lister-item-year text-muted unbold" # ).text.lower()

#if film found (searching using name) if title in name: #scraping rating rating = result.find("div",class_="inline-block ratings-imdb-rating")["data-value"] #scraping genre genre = result.p.find("span", class_="genre") genre = genre.contents[0]

#appending name, rating and genre to individual lists names.append(name1) ratings.append(rating) genres.append(genre)

except Exception: print("Try again with valid combination of tile and release year")

#storing in pandas dataframe``df = pd.DataFrame({'Film Name':names,'Rating':ratings,'Genre':genres})

`#making csv using pandas``df.to_csv(‘film_ratings.csv’, index=False, encoding=‘utf-8’)

24.网络报废 评论


​​​​​​​

from selenium import webdriverimport csvimport time`

items=[]``driver=webdriver.Chrome(r"C:/Users/hp/Anaconda3/chromedriver.exe")

driver.get('https://www.youtube.com/watch?v=iFPMz36std4')

driver.execute_script('window.scrollTo(1, 500);')

#now wait let load the comments``time.sleep(5)

driver.execute_script('window.scrollTo(1, 3000);')

username_elems = driver.find_elements_by_xpath('//*[@id="author-text"]')``comment_elems = driver.find_elements_by_xpath('//*[@id="content-text"]')``for username, comment in zip(username_elems, comment_elems): item = {} item['Author'] = username.text item['Comment'] = comment.text `items.append(item)filename = 'C:/Users/hp/Desktop/commentlist.csv'with open(filename, ‘w’, newline=‘’, encoding=‘utf-8’) as f: w = csv.DictWriter(f,['Author','Comment']) w.writeheader() for item in items: w.writerow(item)

25.文字转语音


文末有福利领取哦~

👉一、Python所有方向的学习路线

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。img

👉二、Python必备开发工具

img
👉三、Python视频合集

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
img

👉 四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。(文末领读者福利)
img

👉五、Python练习题

检查学习结果。
img

👉六、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
img

img

👉因篇幅有限,仅展示部分资料,这份完整版的Python全套学习资料已经上传

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 7
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值