Python基础

  • 简单爬虫例子1

    import requestsfrom bs4 import BeautifulSoupdef fetch_and_parse(url): # 发送HTTP请求到指定URL response = requests.get(url) # 检查请求是否成功 if response.status_code == 200: # 使用BeautifulSoup解析HTML内容 soup = BeautifulSoup(response.text, 'html.parser') # 查找所有的class为"url-card"的div元素 url_cards = soup.find_all('div', {

  • 生成带文字的纯色图片

    from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageFilterdef create_image_with_text(size, color, text, font_path, font_size, text_color, shadow_color, output_path): """ Create a new image of specified size and color with centered text that has a border and shadow. :param size: A tuple con

  • 读取excel表格内容

    import pandas as pddef get_excel_data(file_path): try: # 读取 Excel 文件 df = pd.read_excel(file_path) # 获取表头 headers = df.columns.tolist() # 获取内容并转换为列表的字典,每一行对应一个字典 content = df.to_dict(orient='records') return {'headers': headers, 'content': content} except Exception as e: print(f"读取文件时发生错误: {e}") ret

  • 语音对话

    import waveimport pyaudioimport jsonimport base64import timeimport osimport pyttsx3import baseimport keyboardfrom urllib.request import urlopenfrom urllib.request import Requestfrom openai import OpenAItimer = time.perf_counterAUDIO_FILE = './recorded_audio.pcm'message = [ {"role": "system", "conten

  • 文字转MP3

    import asyncioimport datetimeimport edge_ttsfrom pathlib import Pathdef textToVoice(text): output_file = None # 内部定义异步函数 async def _amain(): nonlocal output_file VOICE = "zh-CN-YunxiNeural" # zh-CN-YunxiNeural zh-CN-XiaoxiaoNeural RATE = "+5%" # 调整语速 communicate = edge_tts.Communicate(text, VOICE, r

  • 文字转语音

    import pyttsx3def speak_text(text): # 初始化pyttsx3库 engine = pyttsx3.init() # 设置语速(可选) rate = engine.getProperty('rate') # 获取当前语速 engine.setProperty('rate', 160) # 设置新的语速 # 设置音量(可选,0.0到1.0之间) volume = engine.getProperty('volume') engine.setProperty('volume', 1.0) # 设置发音人(可选,取决于系统中安装的发音人) voices = engi