首页 > 编程知识 正文

Python实用代码片段

时间:2023-11-20 02:05:24 阅读:304653 作者:EVGC

本文将介绍一些Python实用的代码片段,从多个方面进行阐述。

一、文本处理

1、文本切割

text = "Hello, world! This is a sample text."
words = text.split()
print(words)

运行结果:['Hello,', 'world!', 'This', 'is', 'a', 'sample', 'text.']

上述代码将文本按空格进行切割,返回一个包含所有单词的列表。

2、正则表达式匹配

import re

text = "Hello, 123456 world! This is a sample text."
matches = re.findall(r'd+', text)
print(matches)

运行结果:['123456']

上述代码使用正则表达式匹配文本中的数字串,并返回匹配的结果。

二、文件处理

1、文件读写

# 读取文件
with open('file.txt', 'r') as f:
    lines = f.readlines()

# 写入文件
with open('file_new.txt', 'w') as f:
    for line in lines:
        f.write(line)

上述代码首先使用`with open`语句打开文件并读取所有行,然后使用另一个`with open`语句将读取到的内容写入新文件。

2、文件夹遍历

import os

def list_files(directory):
    file_list = []
    for root, _, files in os.walk(directory):
        for file in files:
            file_list.append(os.path.join(root, file))
    return file_list

files = list_files('path/to/folder')
print(files)

上述代码使用`os.walk`函数遍历给定目录下的所有文件,将文件的绝对路径存入列表并返回。

三、数据处理

1、列表推导

numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]
print(squares)

运行结果:[1, 4, 9, 16, 25]

上述代码使用列表推导生成一个新的列表,每个元素为原列表中对应元素的平方。

2、数据过滤

numbers = [1, 2, 3, 4, 5]
filtered_numbers = [x for x in numbers if x % 2 == 0]
print(filtered_numbers)

运行结果:[2, 4]

上述代码使用条件判断筛选出原列表中的偶数,并生成一个新的列表。

四、网络请求

1、发送GET请求

import requests

response = requests.get('https://api.example.com')
data = response.json()
print(data)

上述代码使用`requests`库发送GET请求,并将返回的JSON响应解析为字典。

2、发送POST请求

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com', data=payload)
data = response.json()
print(data)

上述代码使用`requests`库发送POST请求,并携带表单数据。

五、数据可视化

1、绘制折线图

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.show()

上述代码使用`matplotlib`库绘制一条直线,展示x与y之间的关系。

2、绘制柱状图

import matplotlib.pyplot as plt

x = ['A', 'B', 'C', 'D', 'E']
y = [10, 7, 5, 3, 1]
plt.bar(x, y)
plt.show()

上述代码使用`matplotlib`库绘制一组柱状图,展示不同类别的数量。

六、并发处理

1、多线程

import threading

def print_numbers():
    for i in range(5):
        print(i)

def main():
    t = threading.Thread(target=print_numbers)
    t.start()

if __name__ == '__main__':
    main()

上述代码使用多线程实现并发执行,子线程打印数字0到4。

2、多进程

from multiprocessing import Process

def print_numbers():
    for i in range(5):
        print(i)

def main():
    p = Process(target=print_numbers)
    p.start()

if __name__ == '__main__':
    main()

上述代码使用多进程实现并发执行,子进程打印数字0到4。

七、数据库操作

1、连接数据库

import pymysql

db = pymysql.connect(host='localhost', user='root', passwd='password', db='example')

cursor = db.cursor()
cursor.execute('SELECT * FROM table_name')
result = cursor.fetchall()
print(result)

db.close()

上述代码使用`pymysql`库连接MySQL数据库,并执行查询操作。

2、插入数据

import pymysql

db = pymysql.connect(host='localhost', user='root', passwd='password', db='example')

cursor = db.cursor()
sql = 'INSERT INTO table_name (column1, column2) VALUES (%s, %s)'
values = ('value1', 'value2')
cursor.execute(sql, values)
db.commit()

db.close()

上述代码使用`pymysql`库连接MySQL数据库,并执行插入数据的操作。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。