100个python代码(五)

 

luaCopy code

# 获取环境变量 my_var = os.getenv('MY_VAR') print(my_var) ```

53. 使用requests库处理POST请求: python import requests response = requests.post('https://httpbin.org/post', data = {'key':'value'}) print(response.text)

  1. 使用PIL处理图像:

     

    pythonCopy code

    from PIL import Image im = Image.open("example.jpg") im.rotate(45).show()

  2. 使用pyplot和numpy绘制正弦波:

     

    pythonCopy code

    import numpy as np import matplotlib.pyplot as plt # 生成一个包含360个点的正弦波 x = np.linspace(0, 2 * np.pi, 360) y = np.sin(x) plt.plot(x, y) plt.show()

  3. 使用pandas处理CSV文件:

     

    pythonCopy code

    import pandas as pd df = pd.read_csv("example.csv") print(df.head())

  4. 使用scikit-learn进行线性回归:

     

    pythonCopy code

    from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import pandas as pd # 假设df是一个Pandas DataFrame,包含特征和目标 X = df[['feature1', 'feature2']] y = df['target'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) model = LinearRegression() model.fit(X_train, y_train) print("Model coefficients:", model.coef_)

  5. 使用beautifulsoup解析HTML:

     

    pythonCopy code

    from bs4 import BeautifulSoup import requests URL = "http://example.com/" page = requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") # 打印页面的标题 print(soup.title.text)

  6. 使用pytest参数化测试:

     

    pythonCopy code

    import pytest @pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 54)]) def test_eval(test_input, expected): assert eval(test_input) == expected

  7. 使用flask-restful创建REST API:

     

    pythonCopy code

    from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class HelloWorld(Resource): def get(self): return {'hello': 'world'} api.add_resource(HelloWorld, '/') if __name__ == '__main__': app.run(debug=True)

  8. 使用sqlite3执行查询:

     

    pythonCopy code

    import sqlite3 conn = sqlite3.connect('example.db') c = conn.cursor() # 创建表 c.execute('''CREATE TABLE IF NOT EXISTS stocks (date text, trans text, symbol text, qty real, price real)''') # 插入一行数据 c.execute("INSERT INTO stocks VALUES ('2022-01-05','BUY','RHAT',100,35.14)") # 提交当前事务 conn.commit() # 查询数据 for row in c.execute('SELECT * FROM stocks ORDER BY price'): print(row) conn.close()

  9. 使用matplotlib绘制散点图:

     

    pythonCopy code

    import matplotlib.pyplot as plt x = [5, 7, 8, 5, 6, 7, 9, 2, 3, 4, 4, 4, 2, 6, 3, 6, 8, 6] y = [7, 4, 3, 5, 6, 8, 7, 2, 3, 4, 8, 7, 6, 5, 6, 2, 6, 7] plt.scatter(x, y) plt.show()

  10. 使用正则表达式分割字符串:

     

    pythonCopy code

    import re text = "The rain in Spain" result = re.split(r"\s", text) # 根据空白字符分割 print(result)

  11. 使用glob模块查找文件:

     

    pythonCopy code

    import glob for filename in glob.glob('*.txt'): print(filename

) ```

65. 计算字符串中单词的频率: ```python from collections import Counter

 

scssCopy code

text = "this is a sample text with several words this is a sample text" words = text.split() word_counts = Counter(words) for word, count in word_counts.items(): print(f"{word}: {count}") ```

66. 使用asyncio创建异步任务: ```python import asyncio

 

scssCopy code

async def my_task(seconds): print('This task is taking {} seconds to complete'.format(seconds)) await asyncio.sleep(seconds) return 'task finished' if __name__ == "__main__": loop = asyncio.get_event_loop() task = loop.create_task(my_task(2)) loop.run_until_complete(task) print(task.result()) ```

67. 使用pandas进行数据合并(Merge): ```python import pandas as pd

 

lessCopy code

df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}, index=[0, 1, 2, 3]) df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'], 'B': ['B4', 'B5', 'B6', 'B7'], 'C': ['C4', 'C5', 'C6', 'C7'], 'D': ['D4', 'D5', 'D6', 'D7']}, index=[4, 5, 6, 7]) result = pd.concat([df1, df2]) print(result) ```

68. 使用NumPy创建二维数组: ```python import numpy as np

 

luaCopy code

two_dim_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(two_dim_array) ```

69. 使用matplotlib绘制条形图: ```python import matplotlib.pyplot as plt

 

goCopy code

objects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp') performance = [10,8,6,4,2,1] plt.bar(objects, performance, align='center', alpha=0.5) plt.xticks(objects) plt.ylabel('Usage') plt.title('Programming language usage') plt.show() ```

70. 使用scikit-learn的KMeans进行聚类: ```python from sklearn.cluster import KMeans import numpy as np

 

luaCopy code

X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]) kmeans = KMeans(n_clusters=2, random_state=0).fit(X) print(kmeans.labels_) print(kmeans.predict([[0, 0], [12, 3]])) ```

71. 使用pandas读取Excel文件: ```python import pandas as pd

 

bashCopy code

df = pd.read_excel('example.xlsx', sheet_name='Sheet1') print(df.head()) ```

72. 创建简单的GUI应用程序(tkinter): ```python import tkinter as tk

 

scssCopy code

def say_hello(): print("Hello, World!") app = tk.Tk() app.title("My App") button = tk.Button(app, text="Say Hello", command=say_hello) button.pack() app.mainloop() ```

73. 使用pickle模块进行对象序列化: ```python import pickle

 

pythonCopy code

# 序列化对象 mylist = ['a', 'b', 'c', 'd'] with open('datafile.pkl', 'wb') as f: pickle.dump(mylist, f) # 反序列化对象 with open('datafile.pkl', 'rb') as f: loaded_list = pickle.load(f) print(loaded_list) ```

74. 使用SymPy进行符号计算: ```python from sympy import symbols, Eq, solve

 

scssCopy code

x, y = symbols('x y') equation = Eq(2*x + y, 2) solution = solve(equation, (x, y)) print(solution)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序老猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值