```# Python script to sort files in a directory by their extensionimport osfromshutil import movedef sort_files(directory_path):for filename in os.listdir(directory_path):if os.path.isfile(os.path.join(directory_path, filename)):file_extension = filename.split('.')[-1]destination_directory = os.path.join(directory_path, file_extension)if not os.path.exists(destination_directory):os.makedirs(destination_directory)move(os.path.join(directory_path, filename), os.path.join(destination_directory, filename))```
```# Python script to remove empty folders in a directoryimport osdef remove_empty_folders(directory_path):for root, dirs, files in os.walk(directory_path, topdown=False):for folder in dirs:folder_path = os.path.join(root, folder)if not os.listdir(folder_path):os.rmdir(folder_path)```
```# Python script to rename multiple files in a directoryimport osdef rename_files(directory_path, old_name, new_name):for filename in os.listdir(directory_path):if old_name in filename:new_filename = filename.replace(old_name, new_name)os.rename(os.path.join(directory_path,filename),os.path.join(directory_path, new_filename))```
```# Python script for web scraping to extract data from a websiteimport requestsfrom bs4 import BeautifulSoupdef scrape_data(url):response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')# Your code here to extract relevant data from the website```
```# Python script to download images in bulk from a websiteimport requestsdef download_images(url, save_directory):response = requests.get(url)if response.status_code == 200:images = response.json() # Assuming the API returns a JSON array of image URLsfor index, image_url in enumerate(images):image_response = requests.get(image_url)if image_response.status_code == 200:with open(f"{save_directory}/image_{index}.jpg", "wb") as f:f.write(image_response.content)```
```# Python script to automate form submissions on a websiteimport requestsdef submit_form(url, form_data):response = requests.post(url, data=form_data)if response.status_code == 200:# Your code here to handle the response after form submission```
```# Python script to count words in a text filedef count_words(file_path):with open(file_path, 'r') as f:text = f.read()word_count = len(text.split())return word_count```
```# Python script to find and replace text in a filedef find_replace(file_path, search_text, replace_text):with open(file_path, 'r') as f:text = f.read()modified_text = text.replace(search_text, replace_text)with open(file_path, 'w') as f:f.write(modified_text)```
```# Python script to generate random textimport randomimport stringdef generate_random_text(length):letters = string.ascii_letters + string.digits + string.punctuationrandom_text = ''.join(random.choice(letters) for i in range(length))return random_text```
```# Python script to send personalized emails to a list of recipientsimport smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartdef send_personalized_email(sender_email, sender_password, recipients, subject, body):server = smtplib.SMTP('smtp.gmail.com', 587)server.starttls()server.login(sender_email, sender_password)for recipient_email in recipients:message = MIMEMultipart()message['From'] = sender_emailmessage['To'] = recipient_emailmessage['Subject'] = subjectmessage.attach(MIMEText(body, 'plain'))server.sendmail(sender_email, recipient_email, message.as_string())server.quit()```
```# Python script to send emails with file attachmentsimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBasefrom email import encodersdef send_email_with_attachment(sender_email,sender_password, recipient_email, subject, body, file_path):server = smtplib.SMTP('smtp.gmail.com', 587)server.starttls()server.login(sender_email, sender_password)message = MIMEMultipart()message['From'] = sender_emailmessage['To'] = recipient_emailmessage['Subject'] = subjectmessage.attach(MIMEText(body, 'plain'))with open(file_path, "rb") as attachment:part = MIMEBase('application', 'octet-stream')part.set_payload(attachment.read())encoders.encode_base64(part)part.add_header('Content-Disposition', f"attachment; filename= {file_path}")message.attach(part)server.sendmail(sender_email, recipient_email, message.as_string())server.quit()```
```# Python script to send automatic email remindersimport smtplibfrom email.mime.text import MIMETextfrom datetime import datetime, timedeltadef send_reminder_email(sender_email, sender_password, recipient_email, subject, body, reminder_date):server = smtplib.SMTP('smtp.gmail.com', 587)server.starttls()server.login(sender_email, sender_password)now = datetime.now()reminder_date = datetime.strptime(reminder_date, '%Y-%m-%d')if now.date() == reminder_date.date():message = MIMEText(body, 'plain')message['From'] = sender_emailmessage['To'] = recipient_emailmessage['Subject'] = subjectserver.sendmail(sender_email, recipient_email, message.as_string())server.quit()```
```# Python script to read and write data to an Excel spreadsheetimport pandas as pddef read_excel(file_path):df = pd.read_excel(file_path)return dfdef write_to_excel(data, file_path):df = pd.DataFrame(data)df.to_excel(file_path, index=False)```
```# Python script for data analysis and visualization with pandas and matplotlibimport pandas as pdimport matplotlib.pyplot as pltdef analyze_and_visualize_data(data):# Your code here for data analysis and visualizationpass```
```# Python script to merge multiple Excel sheets into a single sheetimport pandas as pddef merge_sheets(file_path, output_file_path):xls = pd.ExcelFile(file_path)df = pd.DataFrame()for sheet_name in xls.sheet_names:sheet_df = pd.read_excel(xls, sheet_name)df = df.append(sheet_df)df.to_excel(output_file_path, index=False)```
```# Python script to connect to a database and execute queriesimport sqlite3def connect_to_database(database_path):connection = sqlite3.connect(database_path)return connectiondef execute_query(connection, query):cursor = connection.cursor()cursor.execute(query)result = cursor.fetchall()return result```
```# Python script to execute SQL queries on a databaseimport sqlite3def execute_query(connection, query):cursor = connection.cursor()cursor.execute(query)result = cursor.fetchall()return result```
```import shutildef backup_database(database_path, backup_directory):shutil.copy(database_path, backup_directory)def restore_database(backup_path, database_directory):shutil.copy(backup_path, database_directory)```
```# Python script to automate posting on Twitter and Facebookfrom twython import Twythonimport facebookdef post_to_twitter(api_key, api_secret, access_token, access_token_secret, message):twitter = Twython(api_key, api_secret, access_token, access_token_secret)twitter.update_status(status=message)def post_to_facebook(api_key, api_secret, access_token, message):graph = facebook.GraphAPI(access_token)graph.put_object(parent_object='me', connection_name='feed', message=message)```
```# Python script to automatically share content on social media platformsimport randomdef get_random_content():# Your code here to retrieve random content from a list or databasepassdef post_random_content_to_twitter(api_key, api_secret, access_token, access_token_secret):content = get_random_content()post_to_twitter(api_key, api_secret, access_token, access_token_secret, content)def post_random_content_to_facebook(api_key, api_secret, access_token):content = get_random_content()post_to_facebook(api_key, api_secret, access_token, content)```
```# Python script for scraping data from social media platformsimport requestsdef scrape_social_media_data(url):response = requests.get(url)# Your code here to extract relevant data from the response```
```# Python script to manage system processesimport psutildef get_running_processes():return [p.info for p in psutil.process_iter(['pid', 'name', 'username'])]def kill_process_by_name(process_name):for p in psutil.process_iter(['pid', 'name', 'username']):if p.info['name'] == process_name:p.kill()```
```# Python script to schedule tasks using cron syntaxfrom crontab import CronTabdef schedule_task(command, schedule):cron = CronTab(user=True)job = cron.new(command=command)job.setall(schedule)cron.write()```
```# Python script to monitor disk space and send an alert if it's lowimport psutildef check_disk_space(minimum_threshold_gb):disk = psutil.disk_usage('/')free_space_gb = disk.free / (230) # Convert bytes to GBif free_space_gb < minimum_threshold_gb:# Your code here to send an alert (email, notification, etc.)pass```
```# Python script to resize and crop imagesfrom PIL import Imagedef resize_image(input_path, output_path, width, height):image = Image.open(input_path)resized_image = image.resize((width, height), Image.ANTIALIAS)resized_image.save(output_path)def crop_image(input_path, output_path, left, top, right, bottom):image = Image.open(input_path)cropped_image = image.crop((left, top, right, bottom))cropped_image.save(output_path)```
```# Python script to add watermarks to imagesfrom PIL import Imagefrom PIL import ImageDrawfrom PIL import ImageFontdef add_watermark(input_path, output_path, watermark_text):image = Image.open(input_path)draw = ImageDraw.Draw(image)font = ImageFont.truetype('arial.ttf', 36)draw.text((10, 10), watermark_text, fill=(255, 255, 255, 128), font=font)image.save(output_path)```
```# Python script to create image thumbnailsfrom PIL import Imagedef create_thumbnail(input_path, output_path, size=(128, 128)):image = Image.open(input_path)image.thumbnail(size)image.save(output_path)```
```# Python script to check the status of a websiteimport requestsdef check_website_status(url):response = requests.get(url)if response.status_code == 200:# Your code here to handle a successful responseelse:# Your code here to handle an unsuccessful response```
```# Python script to automate FTP file transfersfrom ftplib import FTPdef ftp_file_transfer(host, username, password, local_file_path, remote_file_path):with FTP(host) as ftp:ftp.login(user=username, passwd=password)with open(local_file_path, 'rb') as f:ftp.storbinary(f'STOR {remote_file_path}', f)```
```# Python script to automate network device configurationfrom netmiko import ConnectHandlerdef configure_network_device(host, username, password, configuration_commands):device = {'device_type': 'cisco_ios','host': host,'username': username,'password': password,}with ConnectHandler(device) as net_connect:net_connect.send_config_set(configuration_commands)```
```# Python script to remove duplicates from dataimport pandas as pddef remove_duplicates(data_frame):cleaned_data = data_frame.drop_duplicates()return cleaned_data```
```# Python script for data normalizationimport pandas as pddef normalize_data(data_frame):normalized_data = (data_frame - data_frame.min()) / (data_frame.max() - data_frame.min())return normalized_data```
```# Python script to handle missing values in dataimport pandas as pddef handle_missing_values(data_frame):filled_data = data_frame.fillna(method='ffill')return filled_data```
```# Python script to extract text from PDFsimportPyPDF2def extract_text_from_pdf(file_path):with open(file_path, 'rb') as f:pdf_reader = PyPDF2.PdfFileReader(f)text = ''for page_num in range(pdf_reader.numPages):page = pdf_reader.getPage(page_num)text += page.extractText()return text```
```# Python script to merge multiple PDFs into a single PDFimport PyPDF2def merge_pdfs(input_paths, output_path):pdf_merger = PyPDF2.PdfMerger()for path in input_paths:with open(path, 'rb') as f:pdf_merger.append(f)with open(output_path, 'wb') as f:pdf_merger.write(f)```
```# Python script to add password protection to a PDFimport PyPDF2def add_password_protection(input_path, output_path, password):with open(input_path, 'rb') as f:pdf_reader = PyPDF2.PdfFileReader(f)pdf_writer = PyPDF2.PdfFileWriter()for page_num in range(pdf_reader.numPages):page = pdf_reader.getPage(page_num)pdf_writer.addPage(page)pdf_writer.encrypt(password)with open(output_path, 'wb') as output_file:pdf_writer.write(output_file)```
```# Python script for GUI automation using pyautoguiimport pyautoguidef automate_gui():# Your code here for GUI automation using pyautoguipass```
```# Python script to create simple GUI applications using tkinterimport tkinter as tkdef create_simple_gui():# Your code here to define the GUI elements and behaviorpass```
```# Python script to handle GUI events using tkinterimport tkinter as tkdef handle_gui_events():passdef on_button_click():# Your code here to handle button click eventroot = tk.Tk()button = tk.Button(root, text="Click Me", command=on_button_click)button.pack()root.mainloop()```
```# Python script for unit testing with the unittest moduleimport unittestdef add(a, b):return a + bclass TestAddFunction(unittest.TestCase):def test_add_positive_numbers(self):self.assertEqual(add(2, 3), 5)def test_add_negative_numbers(self):self.assertEqual(add(-2, -3), -5)def test_add_zero(self):self.assertEqual(add(5, 0), 5)if __name__ == '__main__':unittest.main()```
```# Python script for web testing using Seleniumfrom selenium import webdriverdef perform_web_test():driver = webdriver.Chrome()driver.get("https://www.example.com")# Your code here to interact with web elements and perform testsdriver.quit()```
```# Python script for building test automation frameworks# Your code here to define the framework architecture and tools```
```# Python script to automate uploading files to cloud storage# Your code here to connect to a cloud storage service (e.g., AWS S3, Google Cloud Storage)# Your code here to upload files to the cloud storage```
```# Python script to manage AWS resources using Boto3import boto3def create_ec2_instance(instance_type, image_id, key_name, security_group_ids):ec2 = boto3.resource('ec2')instance = ec2.create_instances(ImageId=image_id,InstanceType=instance_type,KeyName=key_name,SecurityGroupIds=security_group_ids,MinCount=1,MaxCount=1)return instance[0].id```
```# Python script to automate interactions with Google Drive# Your code here to connect to Google Drive using the respective API# Your code here to perform tasks such as uploading files, creating folders, etc.```
```# Python script for stock price analysis# Your code here to fetch stock data using a financial API (e.g., Yahoo Finance)# Your code here to analyze the data and derive insights```
```# Python script to fetch currency exchange rates# Your code here to connect to a currency exchange API (e.g., Fixer.io, Open Exchange Rates)# Your code here to perform currency conversions and display exchange rates```
```# Python script for budget tracking and analysis# Your code here to read financial transactions from a CSV or Excel file# Your code here to calculate income, expenses, and savings# Your code here to generate reports and visualize budget data```
```# Python script for sentiment analysis using NLTK or other NLP librariesimportnltkfromnltk.sentiment import SentimentIntensityAnalyzerdefanalyze_sentiment(text):nltk.download('vader_lexicon')sia = SentimentIntensityAnalyzer()sentiment_score = sia.polarity_scores(text)return sentiment_score```
```# Python script for text summarization using NLP techniques# Your code here to read the text data and preprocess it (e.g., removing stop words)# Your code here to generate the summary using techniques like TF-IDF, TextRank, or BERT```
```# Python script for language translation using NLP libraries# Your code here to connect to a translation API (e.g., Google Translate, Microsoft Translator)# Your code here to translate text between different languages```
编辑 / 张志红
审核 / 范瑞强
复核 / 张志红
点击下方
关注我们
版权声明:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权、违法违规、事实不符,请将相关资料发送至xkadmin@xkablog.com进行投诉反馈,一经查实,立即处理!
转载请注明出处,原文链接:https://www.xkablog.com/bcyy/11929.html