返回

10 行 Python 代码的奇妙世界:实现创意十足的任务

后端

Python 因其简洁的语法、丰富的库和广泛的应用而成为当今备受欢迎的编程语言之一。即使是 10 行 Python 代码,也能完成许多令人惊叹的任务。本文将向您展示 10 个有趣的 Python 代码示例,让您领略 Python 的魅力。

任务 1:生成随机密码

import random
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*'
password = ''.join(random.choice(chars) for i in range(10))
print(password)

任务 2:文本反转

def reverse_string(text):
  reversed_text = text[::-1]
  return reversed_text

print(reverse_string('Hello, world!'))

任务 3:素数生成器

def is_prime(number):
  if number <= 1:
    return False
  for i in range(2, int(number ** 0.5) + 1):
    if number % i == 0:
      return False
  return True

def prime_generator():
  number = 2
  while True:
    if is_prime(number):
      yield number
    number += 1

primes = prime_generator()
for i in range(10):
  print(next(primes))

任务 4:图像像素化

from PIL import Image, ImageFilter

image = Image.open('image.jpg')
image = image.filter(ImageFilter.Pixelate(10))
image.save('pixelated_image.jpg')

任务 5:日期和时间处理

from datetime import datetime

now = datetime.now()
print(now.strftime('%Y-%m-%d %H:%M:%S'))

birthday = datetime(1990, 12, 25)
age = now - birthday
print(age.days / 365)

任务 6:文件内容统计

import os

def count_lines_and_words(filename):
  with open(filename, 'r') as file:
    lines = 0
    words = 0
    for line in file:
      lines += 1
      words += len(line.split())
  return lines, words

lines, words = count_lines_and_words('text.txt')
print(f'Lines: {lines}, Words: {words}')

任务 7:查找文件

import os

def find_files(directory, pattern):
  files = []
  for root, directories, filenames in os.walk(directory):
    for filename in filenames:
      if pattern in filename:
        files.append(os.path.join(root, filename))
  return files

files = find_files('directory', 'pattern')
for file in files:
  print(file)

任务 8:数据可视化

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')
plt.show()

任务 9:Web 爬取

import requests
from bs4 import BeautifulSoup

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

for link in soup.find_all('a'):
  print(link.get('href'))

任务 10:字符串加密解密

import base64

message = 'Hello, world!'

encoded_message = base64.b64encode(message.encode('utf-8'))
print(encoded_message)

decoded_message = base64.b64decode(encoded_message).decode('utf-8')
print(decoded_message)

这些仅仅是 Python 强大功能的冰山一角。随着您对 Python 了解更多,您将能够实现更多复杂且有趣的功能。