目錄
- Create strong random passwords
- Extract text from a PDF
- Text processing with Pandoc
- Manipulate audio with Pydub
- Filter text
- Locate addresses
- Convert a CSV to Excel
- Pattern match with regular expressions
- Convert images to JPG
- Compress images
- Get content from Wikipedia
- Create and manage Heroku apps
眾所周知,開發人員的日常工作通常涉及創建和維護小型實用程序腳本。這些腳本是連接系統或構建環境各個方面的粘合劑。雖然這些 Python 腳本可能并不復雜,但維護它們可能會成為一項乏味的苦差事,可能會花費您的時間和金錢。
減輕維護負擔的一種方法是使用腳本自動化。腳本自動化允許您安排這些任務在特定時間表上運行或響應某些事件而觸發,而不是花費時間運行腳本(通常是手動)。
本文將介紹 12 個 Python 腳本,這些腳本是根據其通用實用性、易用性以及對工作負載的積極影響而選擇的。它們的復雜程度從簡單到中級不等,專注于文本處理和文件管理。具體來說,我們將介紹以下用例:
本文中的代碼示例可以在以下位置找到 Here
Create strong random passwords
創建強隨機密碼的原因有很多,從加入新用戶到提供密碼重置工作流程,再到在輪換憑據時創建新密碼。您可以輕松地使用無依賴項的 Python 腳本來自動執行此過程:
# Generate Strong Random Passwords
import random
import string
# This script will generate an 18 character password
word_length = 18
# Generate a list of letters, digits, and some punctuation
components = [string.ascii_letters, string.digits, "!@#$%&"]
# flatten the components into a list of characters
chars = []
for clist in components:for item in clist:chars.append(item)
def generate_password():# Store the generated passwordpassword = []# Choose a random item from 'chars' and add it to 'password'for i in range(word_length):rchar = random.choice(chars)password.append(rchar)# Return the composed password as a stringreturn "".join(password)
# Output generated password
print(generate_password())
Extract text from a PDF
Python 還可以使用 PyPDF2 包輕松地從 PDF 中提取文本。事實證明,從 PDF 文件中獲取文本對于數據挖掘、發票核對或報告生成非常有用,并且只需幾行代碼即可實現提取過程的自動化。您可以在終端中運行 pip install PyPDF2 來安裝該軟件包。以下是使用 Py2PDF2 可以實現的一些示例:
假設您收到一個多頁 PDF 文件,但您只需要第一頁。下面的腳本允許您使用幾行 Python 代碼從 PDF 第一頁中提取文本:
# import module PyPDF2
import PyPDF2
# put 'example.pdf' in working directory
# and open it in read binary mode
pdfFileObj = open('example.pdf', 'rb')
# call and store PdfFileReader
# object in pdfReader
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# to print the total number of pages in pdf
# print(pdfReader.numPages)
# get specific page of pdf by passing
# number since it stores pages in list
# to access first page pass 0
pageObj = pdfReader.getPage(0)
# extract the page object
# by extractText() function
texts = pageObj.extractText()
# print the extracted texts
print(texts)
也許您想從兩個 PDF 文件復制文本并將文本合并到一個新的 PDF 中。您可以使用下面的代碼來完成此操作:
Text processing with Pandoc
Pandoc 是一個功能齊全的命令行工具,允許您在不同格式之間轉換標記。這意味著您可以使用 Pandoc 將 Markdown 文本直接轉換為 docx 或將 MediaWiki 標記轉換為 DocBook。標記格式轉換允許您處理外部內容或用戶提交的信息,而不將數據限制為單一格式。您可以使用 pip 安裝 pandoc 包。以下是一些可以使用 pandoc 執行操作的示例。
首先,假設您收到一個 Markdown 格式的文檔,但需要將其轉換為 PDF。 pandoc 讓這變得簡單:
import pandocin_file = open("example.md", "r").read()
pandoc.write(in_file, file="example.pdf", format="pdf")
或者您可能想將 markdown 文件轉換為 json 對象。您可以使用以下腳本來執行此操作:
import pandoc
md_string = """
# Hello from Markdown**This is a markdown string**
"""
input_string = pandoc.read(md_string)
pandoc.write(input_string, format="json", file="md.json")
您可以在此處找到許多其他示例函數,或者查看 pandoc 包文檔以獲取更多信息。
Manipulate audio with Pydub
Pydub 是一個 Python 包,可讓您操作音頻,包括將音頻轉換為各種文件格式,如 wav 或 mp3。此外,Pydub 可以將音頻文件分割成毫秒樣本,這對于機器學習任務可能特別有用。可以通過在終端中輸入 pip install pydub 來安裝 Pydub。
假設您正在處理音頻,需要確保每個文件都有適當的音量。您可以使用此腳本自動執行該任務:
from pydub import AudioSegmentaudio_file = AudioSegment.from_mp3("example.mp3")
louder_audio_file = audio_file + 18
louder_audio_file.export("example_louder.mp3", format="mp3")
Pydub 有許多本示例中未涵蓋的附加功能。您可以在 Pydub GitHub 存儲庫中找到更多內容。
Filter text
# Filter Text
# Import re module
import re
# Take any string data
string = """a string we are using to filter specific items.
perhaps we would like to match credit card numbers
mistakenly entered into the user input. 4444 3232 1010 8989
and perhaps another? 9191 0232 9999 1111"""# Define the searching pattern
pattern = '(([0-9](\s+)?){4}){4}'# match the pattern with input value
found = re.search(pattern, string)
print(found)
# Print message based on the return value
if found:print("Found a credit card number!")
else:print("No credit card numbers present in input")
Locate addresses
如果您正在處理運輸或交付物流或執行簡單的用戶分析任務,查找地址可能會很有用。首先,通過在終端中運行 pip install geocoder 來安裝地理編碼器。下面的腳本允許您輕松查找任何地址的緯度和經度坐標,或從任何坐標集中查找地址:
import geocoder
address = "1600 Pennsylvania Ave NW, Washington DC USA"
coordinates = geocoder.arcgis(address)
geo = geocoder.arcgis(address)
print(geo.latlng)
# output: [38.89767510765125, -77.03654699820865]# If we want to retrieve the location from a set of coordinates
# perform a reverse query.
location = geocoder.arcgis([38.89767510765125, -77.03654699820865], method="reverse")# output: <[OK] Arcgis - Reverse [White House]>
print(location)
Convert a CSV to Excel
您可能會發現自己經常管理來自分析平臺或數據集的 CSV 文件輸出。在 Excel 中打開 CSV 文件相對簡單,但 Python 允許您通過自動轉換來跳過此手動步驟。這還允許您在轉換為 Excel 之前操作 CSV 數據,從而節省額外的時間和精力。
首先使用 pip install openpyxl 下載 openpyxl 軟件包。安裝 openpyxl 后,您可以使用以下腳本將 CSV 文件轉換為 Excel 電子表格:
#!python3
# -*- coding: utf-8 -*-import openpyxl
import sys#inputs
print("This programme writes the data in any Comma-separated value file (such as: .csv or .data) to a Excel file.")
print("The input and output files must be in the same directory of the python file for the programme to work.\n")csv_name = input("Name of the CSV file for input (with the extension): ")
sep = input("Separator of the CSV file: ")
excel_name = input("Name of the excel file for output (with the extension): ")
sheet_name = input("Name of the excel sheet for output: ")#opening the files
try:wb = openpyxl.load_workbook(excel_name)sheet = wb.get_sheet_by_name(sheet_name)file = open(csv_name,"r",encoding = "utf-8")
except:print("File Error!")sys.exit()#rows and columns
row = 1
column = 1#for each line in the file
for line in file:#remove the \n from the line and make it a list with the separatorline = line[:-1]line = line.split(sep)#for each data in the linefor data in line:#write the data to the cellsheet.cell(row,column).value = data#after each data column number increases by 1column += 1#to write the next line column number is set to 1 and row number is increased by 1column = 1row += 1#saving the excel file and closing the csv file
wb.save(excel_name)
file.close()
Pattern match with regular expressions
從非結構化來源收集數據可能是一個非常乏味的過程。與上面的過濾示例類似,Python 允許使用正則表達式進行更詳細的模式匹配。這對于將文本信息分類為數據處理工作流程的一部分或在用戶提交的內容中搜索特定關鍵字非常有用。內置的正則表達式庫稱為 re,一旦掌握了正則表達式語法,您就可以自動化幾乎所有模式匹配腳本。
例如,也許您想匹配在您正在處理的文本中找到的任何電子郵件地址。您可以使用此腳本來執行此操作:
import re
emailRegex = re.compile(r'''([a-zA-Z0-9._%+-]+ # username@ # @ symbol[a-zA-Z0-9.-]+ # domain name(\.[a-zA-Z]{2,4}) # dot-something)''', re.VERBOSE)# store matched addresses in an array called "matches"
matches = []
text = """
An example text containing an email address, such as user@example.com or something like hello@example.com
"""# search the text and append matched addresses to the "matches" array
for groups in emailRegex.findall(text):matches.append(groups[0])# matches => ['user@example.com', 'hello@example.com']
print(matches)
如果您需要匹配文本中的電話號碼,可以使用此腳本:
import retext = """
Here is an example string containing various numbers, some
of which are not phone numbers.Business Address
4553-A First Street
Washington, DC 20001202-555-6473
301-555-8118
"""phoneRegex = re.compile(r'''((\d{3}|\(\d{3}\))? # area code(\s|-|\.)? # separator(\d{3}) # first 3 digits(\s|-|\.) # separator(\d{4}) # last 4 digits(\s*(ext|x|ext.)\s*(\d{2,5}))? # extension)''', re.VERBOSE)matches = []
for numbers in phoneRegex.findall(text):matches.append(numbers[0])# matches => ['202-555-6473', '301-555-8118']
print(matches)
Convert images to JPG
.jpg 格式可能是當前使用的最流行的圖像格式。您可能會發現自己需要轉換其他格式的圖像以生成項目資產或圖像識別。 Python 的 Pillow 包使得將圖像轉換為 jpg 成為一個簡單的過程:
# requires the Pillow module used as `PIL` below
from PIL import Image
import os
import sys
file="toJPG.png"
filename = file.split(".")
img = Image.open(file)
new_name = filename[0] + ".jpg"
converted_img = img.convert('RGB')
converted_img.save(new_name)
Compress images
有時,您可能需要壓縮圖像作為新站點或臨時登錄頁面的資產創建管道的一部分,并且可能不希望手動執行此操作,或者您必須將任務發送到外部圖像處理服務。使用枕頭包,您可以輕松壓縮 JPG 圖像以減小文件大小,同時保持圖像質量。使用 pip installpillow 安裝pillow。
# the pillow package can be imported as PIL
from PIL import Image
file_path = "image_uncompressed.jpg"
img = Image.open(file_path)
height, width = img.size
compressed = img.resize((height, width), Image.ANTIALIAS)
compressed.save("image_compressed.jpg", optimize=True,quality=9)
Get content from Wikipedia
維基百科對許多主題提供了精彩的總體概述。此信息可用于向交易電子郵件添加附加信息、跟蹤特定文章集的更改或制作培訓文檔或報告。值得慶幸的是,使用 Python 的 Wikipedia 包收集信息也非常容易。
您可以使用 pip install wikipedia 安裝 Wikipedia 包。安裝完成后,您就可以開始了。
如果您已經知道要提取的特定頁面內容,則可以直接從該頁面執行此操作:
import wikipedia
page_content = wikipedia.page("parsec").content
# outputs the text content of the "Parsec" page on wikipedia
print(page_content)
該包還允許您搜索與指定文本匹配的頁面:
import wikipedia
search_results = wikipedia.search("arc second")
# outputs an array of pages matching the search term
print(search_results)
Create and manage Heroku apps
Heroku 是一個用于部署和托管 Web 應用程序的流行平臺。作為一項托管服務,它允許開發人員通過 Heroku API 輕松設置、配置、維護甚至刪除應用程序。您還可以使用 Airplane 運行手冊輕松創建或管理 Heroku 應用程序,因為 Airplane 使訪問 API 和觸發事件變得非常容易。
下面的示例依賴于 heroku3 軟件包,您可以使用 pip install heroku3 安裝該軟件包。請注意,您需要 Heroku API 密鑰才能訪問該平臺。
使用 Python 連接到 Heroku:
import heroku3# Be sure to update the api_key variable with your key
api_key = "12345-ABCDE-67890-FGHIJ"
client = heroku3.from_key(api_key)
連接到 Heroku 后,您可以列出可用的應用程序并選擇要直接管理的應用程序:
import heroku3
api_key = "12345-ABCDE-67890-FGHIJ"
client = heroku3.from_key(api_key)client.apps()# the above command prints an array of available applications
# [<app 'airplanedev-heroku-example - ed544e41-601d-4d1b-a327-9a1945b743cb'>, <app 'notes-app - 5b3d6aab-cde2-4527-9ecc-62bdee08ed4a'>, …] # use the following command to connect to a specific application
app = client.apps()["airplanedev-heroku-example"]# add a config variable for your application
config = app.config()
config["test_var"] = "value"# enable or disable maintenance mode
# enable
app.enable_maintenance_mode()# disable
app.disable_maintenance_mode()# restarting your application is simple
app.restart()
然后,以下腳本將允許您創建一個應用程序作為 Airplane Runbook 的一部分:
import heroku3
api_key = "12345-ABCDE-67890-FABCD"
client = heroku3.from_key(api_key)client.create_app("app-created-with-airplane")