目录
1. 将 JSON 转换为 CSV
安装
2. 密码生成器
3.从多个文件中搜索字符串
4. 获取给定网页的所有链接
安装
5.图像水印
安装
6. 抓取并下载网页上的所有图像
安装
执行脚本
7. 低电量通知
安装
执行脚本
8. 计算你的年龄
执行脚本
9. 按不同类别组织下载文件夹
10.从CSV文件批量发送电子邮件
安装
执行脚本
建议收藏备用
1. 将 JSON 转换为 CSV
该脚本会将您的 JSON 数据转换为 CSV 文件。它接受.json一个文件作为输入并提供.csv该文件作为输出。
安装
pip install json
import jsonif __name__ == '__main__':try:with open('input.json', 'r') as f:data = json.loads(f.read())output = ','.join([*data[0]])for obj in data:output += f'\n{obj["Name"]},{obj["age"]},{obj["birthyear"]}'with open('output.csv', 'w') as f:f.write(output)except Exception as ex:print(f'Error: {str(ex)}')
2. 密码生成器
这个简单的 Python 项目使用random
和string
包来生成给定长度的随机字符串。
import randomimport stringtotal = string.ascii_letters + string.digits + string.punctuationlength = 16password = "".join(random.sample(total, length))print(password)
3.从多个文件中搜索字符串
在您选择的文件夹中查找包含提供的字符串的文件。
import ostext = input("input text : ")path = input("path : ")# os.chdir(path)def getfiles(path):f = 0os.chdir(path)files = os.listdir()# print(files)for file_name in files:abs_path = os.path.abspath(file_name)if os.path.isdir(abs_path):getfiles(abs_path)if os.path.isfile(abs_path):f = open(file_name, "r")if text in f.read():f = 1print(text + " found in ")final_path = os.path.abspath(file_name)print(final_path)return Trueif f == 1:print(text + " not found! ")return Falsegetfiles(path)
4. 获取给定网页的所有链接
该脚本获取来自特定网站的所有链接并将它们保存为文本文件。
安装
pip install beautifulsoup4 requests
import requests as rqfrom bs4 import BeautifulSoupurl = input("Enter Link: ")if ("https" or "http") in url:data = rq.get(url)else:data = rq.get("https://" + url)soup = BeautifulSoup(data.text, "html.parser")links = []for link in soup.find_all("a"):links.append(link.get("href"))# Writing the output to a file (myLinks.txt) instead of to stdout# You can change 'a' to 'w' to overwrite the file each timewith open("myLinks.txt", 'a') as saved:print(links[:10], file=saved)
5.图像水印
该项目将拍摄一张照片并在其上添加您选择的水印。
安装
pip install Pillow
import osfrom PIL import Imagedef watermark_photo(input_image_path,watermark_image_path,output_image_path):base_image = Image.open(input_image_path)watermark = Image.open(watermark_image_path).convert("RGBA")# add watermark to your imageposition = base_image.sizenewsize = (int(position[0]*8/100),int(position[0]*8/100))# print(position)watermark = watermark.resize(newsize)# print(newsize)# return watermarknew_position = position[0]-newsize[0]-20,position[1]-newsize[1]-20# create a new transparent imagetransparent = Image.new(mode='RGBA',size=position,color=(0,0,0,0))# paste the original imagetransparent.paste(base_image,(0,0))# paste the watermark imagetransparent.paste(watermark,new_position,watermark)image_mode = base_image.modeprint(image_mode)if image_mode == 'RGB':transparent = transparent.convert(image_mode)else:transparent = transparent.convert('P')transparent.save(output_image_path,optimize=True,quality=100)print("Saving"+output_image_path+"...")folder = input("Enter Folder Path:")watermark = input("Enter Watermark Path:")os.chdir(folder)files = os.listdir(os.getcwd())print(files)if not os.path.isdir("output"):os.mkdir("output")c = 1for f in files:if os.path.isfile(os.path.abspath(f)):if f.endswith(".png") or f.endswith(".jpg"):watermark_photo(f,watermark,"output/"+f)
6. 抓取并下载网页上的所有图像
该脚本将利用 selenium 和 beautifulsoup4 包从指定网页下载所有照片。
安装
- 我们需要使用 pip python 包管理器安装 selenium 和 beautifulsoup4
pip install selenium beautifulsoup4
。 - 然后根据您的 chrome 浏览器版本和操作系统从此处下载 chrome 驱动程序 —ChromeDriver – WebDriver for Chrome
- 您必须输入程序要求的 chromedriver 路径。
from selenium import webdriverimport requests as rqimport osfrom bs4 import BeautifulSoupimport time# path= E:\web scraping\chromedriver_win32\chromedriver.exepath = input("Enter Path : ")url = input("Enter URL : ")output = "output"def get_url(path, url):driver = webdriver.Chrome(executable_path=r"{}".format(path))driver.get(url)print("loading.....")res = driver.execute_script("return document.documentElement.outerHTML")return resdef get_img_links(res):soup = BeautifulSoup(res, "lxml")imglinks = soup.find_all("img", src=True)return imglinksdef download_img(img_link, index):try:extensions = [".jpeg", ".jpg", ".png", ".gif"]extension = ".jpg"for exe in extensions:if img_link.find(exe) > 0:extension = exebreakimg_data = rq.get(img_link).contentwith open(output + "\\" + str(index + 1) + extension, "wb+") as f:f.write(img_data)f.close()except Exception:passresult = get_url(path, url)time.sleep(60)img_links = get_img_links(result)if not os.path.isdir(output):os.mkdir(output)for index, img_link in enumerate(img_links):img_link = img_link["src"]print("Downloading...")if img_link:download_img(img_link, index)print("Download Complete!!")
执行脚本
要运行以下脚本,您必须打开终端进入脚本的根目录,并需要输入以下命令
python3 scrap-img.py
它会询问您刚刚下载的 chrome 驱动程序路径以及您要从中下载图像的 URL。
7. 低电量通知
此 python 脚本显示有关设备电池百分比的通知。
安装
要运行此脚本,我们需要通过运行以下命令来下载psutil、py-notifier和win10tost 。
1. psutil> pip install psutil2. pynotifier> pip install py-notifier3. win10toast> pip install win10toast
# pip install psutilimport psutilbattery = psutil.sensors_battery()plugged = battery.power_pluggedpercent = battery.percentif percent <= 30 and plugged!=True:# pip install py-notifier# pip install win10toastfrom pynotifier import NotificationNotification(title="Battery Low",description=str(percent) + "% Battery remain!!",duration=5,# Duration in seconds).send()
执行脚本
打开终端进入脚本文件的根目录并运行以下命令
python3 battery.py
8. 计算你的年龄
该脚本以三种不同的方式打印您的年龄:年、月、日
import timefrom calendar import isleap# judge the leap yeardef judge_leap_year(year):if isleap(year):return Trueelse:return False# returns the number of days in each monthdef month_days(month, leap_year):if month in [1, 3, 5, 7, 8, 10, 12]:return 31elif month in [4, 6, 9, 11]:return 30elif month == 2 and leap_year:return 29elif month == 2 and (not leap_year):return 28name = input("input your name: ")age = input("input your age: ")localtime = time.localtime(time.time())year = int(age)month = year * 12 + localtime.tm_monday = 0begin_year = int(localtime.tm_year) - yearend_year = begin_year + year# calculate the daysfor y in range(begin_year, end_year):if (judge_leap_year(y)):day = day + 366else:day = day + 365leap_year = judge_leap_year(localtime.tm_year)for m in range(1, localtime.tm_mon):day = day + month_days(m, leap_year)day = day + localtime.tm_mdayprint("%s's age is %d years or " % (name, year), end="")print("%d months or %d days" % (month, day))
执行脚本
执行脚本非常简单!
只需在包含脚本的文件夹中打开终端并输入以下命令:
python3 calculate.py
然后你必须输入姓名和年龄
input your name: XYZinput your age: 33 Output - XYZ's age is 33 years or 406 months or 12328 days
9. 按不同类别组织下载文件夹
这是一个 Python 脚本,可根据扩展名将下载目录中的文件分类到其他文件夹中。
import osimport shutilos.chdir("E:\downloads")#print(os.getcwd())#check number of files indirectoryfiles = os.listdir()#list of extension (You can add more if you want)extentions = {"images": [".jpg", ".png", ".jpeg", ".gif"],"videos": [".mp4", ".mkv"],"musics": [".mp3", ".wav"],"zip": [".zip", ".tgz", ".rar", ".tar"],"documents": [".pdf", ".docx", ".csv", ".xlsx", ".pptx", ".doc", ".ppt", ".xls"],"setup": [".msi", ".exe"],"programs": [".py", ".c", ".cpp", ".php", ".C", ".CPP"],"design": [".xd", ".psd"]}#sort to specific folder depend on extenstionsdef sorting(file):keys = list(extentions.keys())for key in keys:for ext in extentions[key]:# print(ext)if file.endswith(ext):return key#iterat through each filefor file in files:dist = sorting(file)if dist:try:shutil.move(file, "../download-sorting/" + dist)except:print(file + " is already exist")else:try:shutil.move(file, "../download-sorting/others")except:print(file + " is already exist")
10.从CSV文件批量发送电子邮件
该项目包括一个简单的批量电子邮件脚本,可将相同的消息传递给收件人列表。
安装
该项目仅需要 Python 标准库(更具体地说,是csv
、email
和smtplib
模块)。
import csvfrom email.message import EmailMessageimport smtplibdef get_credentials(filepath):with open("credentials.txt", "r") as f:email_address = f.readline()email_pass = f.readline()return (email_address, email_pass)def login(email_address, email_pass, s):s.ehlo()# start TLS for securitys.starttls()s.ehlo()# Authentications.login(email_address, email_pass)print("login")def send_mail():s = smtplib.SMTP("smtp.gmail.com", 587)email_address, email_pass = get_credentials("./credentials.txt")login(email_address, email_pass, s)# message to be sentsubject = "Welcome to Python"body = """Python is an interpreted, high-level,general-purpose programming language.\nCreated by Guido van Rossum and first released in 1991,Python's design philosophy emphasizes code readability\nwith its notable use of significant whitespace"""message = EmailMessage()message.set_content(body)message['Subject'] = subjectwith open("emails.csv", newline="") as csvfile:spamreader = csv.reader(csvfile, delimiter=" ", quotechar="|")for email in spamreader:s.send_message(email_address, email[0], message)print("Send To " + email[0])# terminating the sessions.quit()print("sent")if __name__ == "__main__":send_mail()
执行脚本
该脚本需要使用两个配置文件:
- emails.csv应包含邮件应发送到的电子邮件地址。
- credentials.txt应包含您的 SMTP 服务器登录凭据,其中您的用户名和密码位于单独的行上,并且没有额外的空格或装饰。
项目目录包含两个示例文件,您几乎肯定希望并需要更改它们。
一旦你准备好这些文件,你所要做的就是
python Send_emails.py
汇总连接:
50个开发必备的Python经典脚本(1-10)
50个开发必备的Python经典脚本(11-20)
50个开发必备的Python经典脚本(21-30)
50个开发必备的Python经典脚本(31-40)
50个开发必备的Python经典脚本(41-50)