python代码大全

Python是一种高级编程语言,属于通用编程语言。它是由荷兰人Guido van Rossum在1989年创造的,其语法简单、易读易写,是一种解释型、面向对象、动态数据类型的编程语言,支持多种编程范式,如面向对象、函数式、过程化等。Python在人工智能、数据科学、Web开发、自动化测试等领域广泛应用,拥有丰富的开源库和工具。因为其易学易用的特点,Python已经成为了编程初学者的首选语言之一。

以下是一些Python代码示例:

1、Hello World程序

print("Hello, World!")

2、列表排序

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

sorted_list = sorted(my_list)

print(sorted_list)

3、字符串拼接

name = "John"

age = 23

print("My name is " + name + " and I am " + str(age) + " years old.")

4、文件读取

with open("file.txt", "r") as f:

    contents = f.read()

print(contents)

5、数据库连接

import sqlite3

conn = sqlite3.connect('example.db')

c = conn.cursor()

c.execute('''CREATE TABLE stocks

             (date text, trans text, symbol text, qty real, price real)''')

conn.commit()

conn.close()

6、爬虫

import requests

from bs4 import BeautifulSoup

url = 'https://www.python.org/'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

print(soup.title.string)

7、数据分析

import pandas as pd

import matplotlib.pyplot as plt

df = pd.read_csv('data.csv')

df.plot(kind='scatter', x='age', y='income')

plt.show()

8、循环结构

for i in range(10):

    print(i)

9、函数定义

def add(x, y):

    return x + y

result = add(3, 5)

print(result)

10、类定义

class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age

    def say_hello(self):

        print("Hello, my name is " + self.name)

person = Person("John", 23)

person.say_hello()

11、GUI程序

import tkinter as tk

window = tk.Tk()

window.title("My App")

label = tk.Label(text="Hello, World!")

label.pack()

window.mainloop()

12、图像处理

from PIL import Image

image = Image.open("image.jpg")

image.show()

13、发送邮件

import smtplib

from email.mime.text import MIMEText

msg = MIMEText("Hello, this is a test email.")

msg['Subject'] = 'Test Email'

msg['From'] = 'sender@example.com'

msg['To'] = 'recipient@example.com'

s = smtplib.SMTP('localhost')

s.send_message(msg)

s.quit()

  1. 时间日期处理

import datetime

now = datetime.datetime.now()

print(now.strftime("%Y-%m-%d %H:%M:%S"))

15、正则表达式

import re

text = "The quick brown fox jumps over the lazy dog."

result = re.findall(r"\b\w{4}\b", text)

print(result)

16、文件写入

with open("file.txt", "w") as f:

    f.write("Hello, World!")

17、多线程

import threading

def worker():

    print("Worker Thread")

threads = []

for i in range(5):

    t = threading.Thread(target=worker)

    threads.append(t)

    t.start()

for t in threads:

    t.join()

18、数据可视化

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [1, 4, 9, 16, 25]

plt.plot(x, y)

plt.xlabel('X Label')

plt.ylabel('Y Label')

plt.title('My Plot')

plt.show()

19、网络爬虫

import requests

from bs4 import BeautifulSoup

url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

title = soup.find('h1', {'id': 'firstHeading'}).text

print(title)

20、机器学习

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split

from sklearn.neighbors import KNeighborsClassifier

iris = load_iris()

X_train, X_test, y_train, y_test = train_test_split(iris['data'], iris['target'], random_state=0)

knn = KNeighborsClassifier(n_neighbors=1)

knn.fit(X_train, y_train)

print(knn.score(X_test, y_test))

21、多进程

import multiprocessing

def worker():

    print("Worker Process")

if __name__ == '__main__':

    processes = []

    for i in range(5):

        p = multiprocessing.Process(target=worker)

        processes.append(p)

        p.start()

    for p in processes:

        p.join()

22、音频处理

import librosa

audio, sr = librosa.load("audio.wav")

print(librosa.feature.mfcc(audio, sr=sr))

23、数据库操作

import sqlite3

conn = sqlite3.connect('example.db')

c = conn.cursor()

c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

conn.commit()

conn.close()

24、自然语言处理

import nltk

text = "The quick brown fox jumps over the lazy dog."

tokens = nltk.word_tokenize(text)

print(nltk.pos_tag(tokens))

25、人脸识别

import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

img = cv2.imread('image.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for (x,y,w,h) in faces:

    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

cv2.imshow

26、数据清洗

import pandas as pd

data = pd.read_csv('data.csv')

data.drop_duplicates(inplace=True)

data.fillna(method='ffill', inplace=True)

27、机器视觉

import cv2

cap = cv2.VideoCapture(0)

while True:

    ret, frame = cap.read()

    cv2.imshow('Frame', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):

        break

cap.release()

cv2.destroyAllWindows()

28、网络通信

import socket

HOST = '127.0.0.1'

PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

    s.bind((HOST, PORT))

    s.listen()

    conn, addr = s.accept()

    with conn:

        print('Connected by', addr)

        while True:

            data = conn.recv(1024)

            if not data:

                break

            conn.sendall(data)

29、云计算

import boto3

s3 = boto3.resource('s3')

s3.create_bucket(Bucket='my-bucket')

bucket = s3.Bucket('my-bucket')

bucket.put_object(Key='test.txt', Body=b'Hello, World!')

for obj in bucket.objects.all():

    print(obj.key)

30、数学计算

import numpy as np

a = np.array([[1, 2], [3, 4]])

b = np.array([[5, 6], [7, 8]])

print(np.dot(a, b))