python有趣代码
生成彩色文本:
pythonclass colors:
RESET = '3[0m'
BOLD = '3[1m'
UNDERLINE = '3[4m'
RED = '3[91m'
GREEN = '3[92m'
YELLOW = '3[93m'
BLUE = '3[94m'
PURPLE = '3[95m'
CYAN = '3[96m'
print(colors.RED + "Hello, this is in red!" + colors.RESET)
绘制彩色螺旋:
pythonimport turtle
from colorsys import hsv_to_rgb
turtle.speed(0)
turtle.bgcolor('black')
for i in range(360 * 10):
turtle.color(*hsv_to_rgb(i / 360, 1.0, 1.0))
turtle.forward(i)
turtle.left(59)
turtle.done()
使用Pygame创建简单的游戏:
pythonimport pygame
import sys
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("My Game")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((255, 255, 255)) # White background
pygame.draw.circle(screen, (255, 0, 0), (400, 300), 30) # Red circle
pygame.display.flip()
使用Matplotlib绘制三维图形:
pythonimport numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='3D spiral')
ax.legend()
plt.show()
文本艺术生成器:
pythonfrom art import *
text = "Hello, ASCII Art!"
result = text2art(text)
print(result)
在运行这个代码之前,你需要安装 art
库。可以使用
bashpip install art
这个库可以将普通文本转换成ASCII艺术风格。
爬取猫咪图片:
pythonimport requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
url = "https://www.reddit.com/r/aww/top/?t=week"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
for i, post in enumerate(soup.find_all('div', class_='s1okktje-0')):
image_url = post.find('img')['src']
image_url = urljoin(url, image_url)
response = requests.get(image_url)
with open(f'cat_{i+1}.jpg', 'wb') as f:
f.write(response.content)
这个代码使用 requests
和 BeautifulSoup
库从Reddit上抓取一周内最受欢迎的猫咪图片。
使用Python进行情感分析:
pythonfrom textblob import TextBlob
text = "I love coding with Python!"
analysis = TextBlob(text)
print(f"Text: {text}")
print(f"Sentiment: {'Positive' if analysis.sentiment.polarity > 0 else 'Negative' if analysis.sentiment.polarity < 0 else 'Neutral'}")
这段代码使用 textblob
库对文本进行情感分析,判断文本的情感是积极、消极还是中性。
使用Flask创建一个简单的Web应用:
pythonfrom flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
这是一个使用 Flask 创建的极简单Web应用。运行代码后,访问 http://127.0.0.1:5000/ 就可以看到 "Hello, World!"。