大家好!今天给大家带来一系列简单却实用的Python小脚本,让你的编程生活更加便捷!🌟
首先,我们来看一个简单的脚本,它可以用来快速生成随机密码。这对于设置新账户或者需要更改密码时非常有用。🔑
```python
import random
import string
def generate_password(length=8):
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(characters) for i in range(length))
print(generate_password())
```
接下来,让我们看看如何用Python来批量重命名文件。这对于整理大量文件来说简直是神器!🗂️
```python
import os
def batch_rename(directory, old_pattern, new_name):
for filename in os.listdir(directory):
if old_pattern in filename:
new_filename = filename.replace(old_pattern, new_name)
os.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))
batch_rename('/path/to/directory', 'old', 'new')
```
最后,我们来看看如何使用Python来统计一段文本中每个单词出现的次数。这对于数据分析和自然语言处理非常有帮助。📚
```python
from collections import Counter
def word_count(text):
words = text.split()
return Counter(words)
text = "This is a simple example to demonstrate the usage of word count."
print(word_count(text))
```
希望这些小脚本能够帮到你!如果你有任何问题或建议,请留言告诉我。💬
Python 编程小技巧 日常工具