🐍 Python 篇
1. 批量重命名文件
import os
# 把当前文件夹下所有 .txt 文件改为 .md
for filename in os.listdir('.'):
if filename.endswith('.txt'):
new_name = filename.replace('.txt', '.md')
os.rename(filename, new_name)
print(f'已重命名: {filename} → {new_name}')
2. 简易计算器
def calculator(a, b, op):
if op == '+': return a + b
if op == '-': return a - b
if op == '*': return a * b
if op == '/': return a / b if b != 0 else '除数不能为0'
print(calculator(10, 5, '+')) # 15
print(calculator(10, 5, '/')) # 2.0
3. 爬取网页标题
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
print(f'网页标题: {soup.title.string}')
🌐 JavaScript 篇
4. 深拷贝对象
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
const original = { name: 'Alice', hobbies: ['reading', 'coding'] };
const cloned = deepClone(original);
cloned.hobbies.push('gaming');
console.log(original.hobbies); // ['reading', 'coding'](原对象不受影响)
5. 防抖函数(优化搜索输入)
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
// 用法:输入停止500ms后才执行
const search = debounce((keyword) => {
console.log('搜索:', keyword);
}, 500);
6. 数组去重(三种写法)
const arr = [1, 2, 2, 3, 4, 4, 5];
// 方法1:Set
const unique1 = [...new Set(arr)];
// 方法2:filter
const unique2 = arr.filter((item, index) => arr.indexOf(item) === index);
// 方法3:reduce
const unique3 = arr.reduce((acc, cur) => {
return acc.includes(cur) ? acc : [...acc, cur];
}, []);
console.log(unique1); // [1, 2, 3, 4, 5]
☕ Java 篇
7. 读取文件内容
import java.nio.file.*;
import java.io.IOException;
public class FileReader {
public static void main(String[] args) {
try {
String content = Files.readString(Path.of("example.txt"));
System.out.println(content);
} catch (IOException e) {
System.out.println("文件读取失败: " + e.getMessage());
}
}
}
8. Lambda 排序
import java.util.*;
public class SortExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// 按长度排序
names.sort((a, b) -> a.length() - b.length());
System.out.println(names); // [Bob, Alice, Charlie]
// 方法引用写法
names.sort(Comparator.comparingInt(String::length));
}
}
🐍 Python 篇
1. 批量重命名文件
2. 简易计算器
3. 爬取网页标题
🌐 JavaScript 篇
4. 深拷贝对象
5. 防抖函数(优化搜索输入)
6. 数组去重(三种写法)
☕ Java 篇
7. 读取文件内容
8. Lambda 排序