Python脚本如何生成随机数据

wen 实用脚本 1

本文目录导读:

Python脚本如何生成随机数据

  1. 基础随机数生成
  2. 生成各种类型随机数据
  3. 生成结构化数据(CSV/JSON)
  4. 使用第三方库(需要安装)
  5. 完整示例:生成产品数据
  6. 生成特定格式数据
  7. 推荐使用场景

我来介绍几种在Python中生成随机数据的方法:

基础随机数生成

import random
import string
# 随机整数
random_int = random.randint(1, 100)  # 1-100之间的随机整数
# 随机浮点数
random_float = random.uniform(1.0, 10.0)  # 1.0-10.0之间的浮点数
# 从列表中随机选择
choice = random.choice(['A', 'B', 'C', 'D'])
# 随机打乱列表
list_example = [1, 2, 3, 4, 5]
random.shuffle(list_example)
# 随机字符串
random_string = ''.join(random.choices(string.ascii_letters, k=8))

生成各种类型随机数据

import random
import string
import datetime
class RandomDataGenerator:
    @staticmethod
    def random_name(length=5):
        """生成随机中文名"""
        first_names = ['赵', '钱', '孙', '李', '周', '吴', '郑', '王']
        last_names = ['明', '华', '强', '伟', '芳', '娜', '秀英', '志强']
        return random.choice(first_names) + random.choice(last_names)
    @staticmethod
    def random_email():
        """生成随机邮箱"""
        domains = ['gmail.com', '163.com', 'qq.com', 'outlook.com']
        username = ''.join(random.choices(string.ascii_lowercase, k=8))
        return f"{username}@{random.choice(domains)}"
    @staticmethod
    def random_phone():
        """生成随机手机号"""
        prefixes = ['138', '139', '150', '151', '188', '186']
        suffix = ''.join(random.choices(string.digits, k=8))
        return random.choice(prefixes) + suffix
    @staticmethod
    def random_date(start_year=2020, end_year=2024):
        """生成随机日期"""
        start = datetime.date(start_year, 1, 1)
        end = datetime.date(end_year, 12, 31)
        days = (end - start).days
        random_days = random.randint(0, days)
        return start + datetime.timedelta(days=random_days)
    @staticmethod
    def random_address():
        """生成随机地址"""
        cities = ['北京', '上海', '广州', '深圳', '杭州']
        streets = ['中山路', '人民路', '解放路', '建设路']
        return f"{random.choice(cities)}市{random.choice(streets)}{random.randint(1, 999)}号"
# 使用示例
generator = RandomDataGenerator()
print(f"姓名: {generator.random_name()}")
print(f"邮箱: {generator.random_email()}")
print(f"手机: {generator.random_phone()}")
print(f"日期: {generator.random_date()}")
print(f"地址: {generator.random_address()}")

生成结构化数据(CSV/JSON)

import csv
import json
import random
from datetime import datetime, timedelta
def generate_user_data(num_records=100):
    """生成用户数据"""
    users = []
    for i in range(1, num_records + 1):
        user = {
            'id': i,
            'name': f'用户{i:03d}',
            'age': random.randint(18, 60),
            'gender': random.choice(['男', '女']),
            'email': f'user{i:03d}@example.com',
            'salary': round(random.uniform(5000, 30000), 2),
            'department': random.choice(['技术部', '市场部', '人事部', '财务部']),
            'created_at': datetime.now() - timedelta(days=random.randint(1, 365))
        }
        users.append(user)
    return users
def save_to_csv(data, filename='users.csv'):
    """保存为CSV文件"""
    if not data:
        return
    keys = data[0].keys()
    with open(filename, 'w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=keys)
        writer.writeheader()
        writer.writerows(data)
def save_to_json(data, filename='users.json'):
    """保存为JSON文件"""
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2, default=str)
# 生成并保存数据
users = generate_user_data(50)
save_to_csv(users)
save_to_json(users)
print(f"生成了 {len(users)} 条用户数据")

使用第三方库(需要安装)

Faker库(最常用的随机数据生成库)

# pip install faker
from faker import Faker
fake = Faker('zh_CN')  # 设置为中文
# 生成各种数据
name = fake.name()
address = fake.address()
phone = fake.phone_number()
email = fake.email()
text = fake.text()
company = fake.company()
job = fake.job()
credit_card = fake.credit_card_number()
# 批量生成
fake_users = [{
    'name': fake.name(),
    'phone': fake.phone_number(),
    'email': fake.email(),
    'company': fake.company(),
    'address': fake.address()
} for _ in range(10)]

Numpy + Pandas

import numpy as np
import pandas as pd
# 生成大量数值数据
n_samples = 1000
data = {
    'feature_1': np.random.normal(0, 1, n_samples),  # 正态分布
    'feature_2': np.random.uniform(-5, 5, n_samples),  # 均匀分布
    'category': np.random.choice(['A', 'B', 'C'], n_samples),
    'timestamp': pd.date_range('2024-01-01', periods=n_samples, freq='H')
}
df = pd.DataFrame(data)
print(df.head())

完整示例:生成产品数据

import random
from faker import Faker
fake = Faker('zh_CN')
def generate_product_data(num_products=100):
    """生成产品数据"""
    categories = ['电子产品', '服装', '食品', '图书', '家居用品']
    payment_methods = ['支付宝', '微信支付', '银行卡', '现金']
    statuses = ['待付款', '已付款', '已发货', '已完成', '已取消']
    products = []
    for i in range(1, num_products + 1):
        product = {
            'product_id': f'P{i:05d}',
            'name': f'{random.choice(categories)}-{i:03d}',
            'category': random.choice(categories),
            'price': round(random.uniform(10, 10000), 2),
            'stock': random.randint(0, 1000),
            'rating': round(random.uniform(1, 5), 1),
            'created_date': fake.date_between(start_date='-1y', end_date='today'),
            'supplier': fake.company(),
            'description': fake.text(max_nb_chars=100),
            'is_active': random.choice([True, False])
        }
        products.append(product)
    return products
# 生成并显示
products = generate_product_data(5)
for product in products:
    print(json.dumps(product, ensure_ascii=False, indent=2, default=str))

生成特定格式数据

import uuid
import hashlib
def generate_special_data():
    """生成特殊格式数据"""
    # UUID
    id = str(uuid.uuid4())
    # 哈希值
    hash_value = hashlib.md5(str(random.random()).encode()).hexdigest()
    # IP地址
    ip = f"{random.randint(1, 255)}.{random.randint(0, 255)}." \
         f"{random.randint(0, 255)}.{random.randint(1, 255)}"
    # 身份证号(仅示例格式)
    def generate_id_card():
        # 前6位地区码
        area = '110101'
        # 出生日期
        birth = f"{random.randint(1970, 2000)}" \
                f"{random.randint(1, 12):02d}" \
                f"{random.randint(1, 28):02d}"
        # 后4位随机
        suffix = ''.join(random.choices(string.digits, k=4))
        return area + birth + suffix
    return {
        'uuid': id,
        'hash': hash_value,
        'ip': ip,
        'id_card': generate_id_card()
    }
print(generate_special_data())

推荐使用场景

  1. 简单数据:使用内置的 random 模块
  2. 模拟真实数据:使用 Faker 库(最推荐)
  3. 大量数值数据:使用 NumPy
  4. 数据科学场景:使用 Pandas + NumPy

最常用的第三方库是 Faker,它支持多种语言和数据格式,非常适合生成测试数据。

抱歉,评论功能暂时关闭!