用脚本生成随机汉字串

wen 实用脚本 2

这是您需要的随机汉字串生成脚本,它基于HTML和JavaScript,可在线运行,方便您批量生成不重复的汉字组合。

用脚本生成随机汉字串

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">随机汉字串生成器</title>
    <style>
        * {
            box-sizing: border-box;
        }
        body {
            background: linear-gradient(145deg, #f7f9fc 0%, #e9edf2 100%);
            font-family: 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
        }
        .card {
            background: rgba(255, 255, 255, 0.75);
            backdrop-filter: blur(6px);
            border-radius: 48px;
            padding: 2.8rem 2.5rem;
            max-width: 800px;
            width: 100%;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.08), 0 8px 16px rgba(0, 0, 0, 0.04);
            transition: all 0.2s ease;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        h1 {
            font-weight: 500;
            font-size: 2rem;
            letter-spacing: -0.5px;
            color: #1a2634;
            margin: 0 0 0.25rem 0;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .sub {
            color: #5a6b7c;
            font-weight: 400;
            font-size: 0.95rem;
            margin-top: -0.2rem;
            margin-bottom: 2rem;
            border-left: 3px solid #9aaec2;
            padding-left: 16px;
        }
        .control-panel {
            display: flex;
            flex-wrap: wrap;
            align-items: flex-end;
            gap: 18px 20px;
            margin-bottom: 28px;
        }
        .control-group {
            display: flex;
            flex-direction: column;
            gap: 6px;
            flex: 1 0 140px;
        }
        .control-group label {
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.4px;
            color: #3d4e5f;
            font-weight: 600;
        }
        .control-group input, .control-group select {
            background: white;
            border: 1px solid #d0d9e3;
            border-radius: 28px;
            padding: 10px 18px;
            font-size: 1rem;
            font-weight: 500;
            color: #1f2a36;
            outline: none;
            transition: 0.2s;
            box-shadow: inset 0 2px 4px rgba(0,0,0,0.02);
        }
        .control-group input:focus, .control-group select:focus {
            border-color: #4f7aa6;
            box-shadow: 0 0 0 3px rgba(79, 122, 166, 0.2);
        }
        .control-group input[type="number"] {
            width: 100%;
            -moz-appearance: textfield;
        }
        .control-group input[type="number"]::-webkit-inner-spin-button {
            opacity: 0.8;
        }
        .actions {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-top: 6px;
            align-items: center;
        }
        .btn {
            background: white;
            border: none;
            padding: 10px 28px;
            border-radius: 40px;
            font-weight: 600;
            font-size: 0.95rem;
            color: #1f2a36;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.02), 0 2px 4px rgba(0, 0, 0, 0.02);
            border: 1px solid #dae1ea;
            cursor: pointer;
            transition: all 0.15s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: #f8faff;
            flex: 0 0 auto;
        }
        .btn-primary {
            background: #2c3e4e;
            border: 1px solid #1f2f3d;
            color: white;
            box-shadow: 0 8px 14px rgba(44, 62, 78, 0.15);
        }
        .btn-primary:hover {
            background: #1f2f3d;
            transform: scale(0.98);
            box-shadow: 0 4px 10px rgba(0,0,0,0.15);
        }
        .btn-secondary {
            background: #eef3f9;
            border: 1px solid #ccd7e4;
        }
        .btn-secondary:hover {
            background: #e2e9f2;
            transform: scale(0.98);
        }
        .output-area {
            background: #ffffffcc;
            backdrop-filter: blur(2px);
            border-radius: 28px;
            padding: 24px 28px;
            margin: 24px 0 18px 0;
            border: 1px solid #dae2ec;
            box-shadow: inset 0 2px 6px rgba(0,0,0,0.02);
            word-break: break-all;
            min-height: 120px;
            display: flex;
            align-items: center;
            font-size: 1.6rem;
            line-height: 1.6;
            letter-spacing: 1px;
            color: #1f2b38;
            font-weight: 450;
            transition: 0.15s;
        }
        .output-area:empty::before {
            content: "点击 “生成” 或调整参数自动更新";
            color: #98aabc;
            font-size: 1.1rem;
            font-weight: 400;
            letter-spacing: 0.2px;
            opacity: 0.7;
        }
        .stat {
            display: flex;
            justify-content: flex-end;
            font-size: 0.85rem;
            color: #4a627a;
            padding-right: 8px;
            margin-top: -8px;
            margin-bottom: 6px;
            gap: 20px;
        }
        .stat span {
            background: #e6edf6;
            padding: 4px 18px;
            border-radius: 40px;
        }
        .footer-note {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
            border-top: 1px solid #d7e0ea;
            margin-top: 22px;
            padding-top: 18px;
            font-size: 0.8rem;
            color: #60758b;
        }
        @media (max-width: 500px) {
            .card { padding: 1.8rem 1.2rem; }
            .output-area { font-size: 1.3rem; padding: 18px; }
            .control-group { flex: 1 0 100%; }
        }
    </style>
</head>
<body>
    <div class="card">
        <h1>⿻ 汉字串</h1>
        <div class="sub">随机 · 可调节长度 · 去重可选</div>
        <div class="control-panel">
            <div class="control-group">
                <label for="lengthInput">长度</label>
                <input type="number" id="lengthInput" value="8" min="1" max="999">
            </div>
            <div class="control-group">
                <label for="countInput">生成数量</label>
                <input type="number" id="countInput" value="3" min="1" max="50">
            </div>
            <div class="control-group">
                <label for="uniqueSelect">字符去重</label>
                <select id="uniqueSelect">
                    <option value="off">关闭</option>
                    <option value="on" selected>开启 (串内无重复)</option>
                </select>
            </div>
            <div class="actions">
                <button class="btn btn-primary" id="generateBtn">✦ 生成</button>
                <button class="btn btn-secondary" id="copyBtn">📋 复制</button>
            </div>
        </div>
        <div class="stat" id="statInfo">
            <span id="statLength">长度 8</span>
            <span id="statCount">数量 3</span>
        </div>
        <!-- 输出区域:显示生成的汉字串,用换行分隔 -->
        <div class="output-area" id="outputArea"></div>
        <div class="footer-note">
            <span>🔤 汉字范围: 常用字 (GB2312)</span>
            <span style="display: flex; gap: 10px;">
                <label style="display: flex; align-items: center; gap: 4px;">
                    <input type="checkbox" id="autoUpdate" checked> 自动更新
                </label>
            </span>
        </div>
    </div>
    <script>
        (function() {
            // ---------- 汉字字库 (GB2312 一级常用字 3755个) ----------
            // 为了生成更真实的汉字串,选用标准的常用汉字区域 (0xB0A1-0xD7F9 部分)
            // 构造一个包含常用汉字的数组 (约 3755 个)
            function buildChineseCharset() {
                const chars = [];
                // GB2312 区位: 16-55区 (一级汉字)
                // 起始区码 0xB0 (176) 位码 0xA1 (161) 
                for (let row = 0xB0; row <= 0xD7; row++) {
                    // 最后一个区0xD7只到0xF9, 但大多数区域0xA1-0xFE
                    const startCol = (row === 0xD7) ? 0xA1 : 0xA1;
                    const endCol   = (row === 0xD7) ? 0xF9 : 0xFE;
                    for (let col = startCol; col <= endCol; col++) {
                        // 跳过非汉字区域 (实际上GB2312一级汉字全部在16-55区, 对应0xB0-0xD7, 且无空白)
                        // 另外第55区(0xD7) 最后部分不是汉字,不过我们包含大部分
                        // 为了更精准,可以限制区域, 但少几个不影响
                        const bytes = new Uint8Array([row, col]);
                        try {
                            const decoder = new TextDecoder('gb2312');
                            const char = decoder.decode(bytes);
                            // 过滤掉非汉字或控制字符 (一般不会是控制字符)
                            if (char && char.length === 1 && /[\u4e00-\u9fff]/.test(char)) {
                                chars.push(char);
                            }
                        } catch (e) {
                            // 忽略解码失败
                        }
                    }
                }
                // 去重 (理论上无重复,但稳妥)
                return [...new Set(chars)];
            }
            // 初始化字库 (加载一次)
            const chineseChars = buildChineseCharset();
            // 备选: 若字库意外较小(边缘情况),补一些常用字
            if (chineseChars.length < 2000) {
                const fallback = '的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济级府装双声快等'.split('');
                chineseChars.push(...fallback);
            }
            // DOM 元素
            const outputArea = document.getElementById('outputArea');
            const lengthInput = document.getElementById('lengthInput');
            const countInput = document.getElementById('countInput');
            const uniqueSelect = document.getElementById('uniqueSelect');
            const generateBtn = document.getElementById('generateBtn');
            const copyBtn = document.getElementById('copyBtn');
            const autoUpdateCheck = document.getElementById('autoUpdate');
            const statLength = document.getElementById('statLength');
            const statCount = document.getElementById('statCount');
            // 辅助: 随机整数 [min, max]
            function randomInt(min, max) {
                return Math.floor(Math.random() * (max - min + 1)) + min;
            }
            // 核心: 生成一个随机汉字串 (length > 0)
            function generateOneString(length, unique) {
                if (length <= 0) return '';
                // 如果去重开启,但请求长度超过字库大小,只能返回字库全部 (去重无解)
                const maxLength = chineseChars.length;
                if (unique === 'on' && length > maxLength) {
                    // 自动降级:返回不重复但长度受限 (全部字库打乱)
                    const shuffled = [...chineseChars];
                    for (let i = shuffled.length - 1; i > 0; i--) {
                        const j = Math.floor(Math.random() * (i + 1));
                        [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
                    }
                    return shuffled.join('');
                }
                if (unique === 'on') {
                    // 从字库中随机选 length 个不重复字符 (Fisher–Yates 取样)
                    const pool = [...chineseChars];
                    const result = [];
                    for (let i = 0; i < length; i++) {
                        // 随机选一个剩余字符
                        const remaining = pool.length - i;
                        const idx = randomInt(0, remaining - 1);
                        // 交换到已选区域末尾 (实际上我们只需取)
                        const selected = pool[idx];
                        result.push(selected);
                        // 将选中的与当前最后未处理的交换 (保持池前段未选)
                        [pool[idx], pool[pool.length - 1 - i]] = [pool[pool.length - 1 - i], pool[idx]];
                    }
                    return result.join('');
                } else {
                    // 不要求唯一: 随机从字库中取 length 次 (可能重复)
                    let str = '';
                    for (let i = 0; i < length; i++) {
                        const idx = randomInt(0, chineseChars.length - 1);
                        str += chineseChars[idx];
                    }
                    return str;
                }
            }
            // 生成全部结果 (多行)
            function generateAll() {
                const length = parseInt(lengthInput.value, 10) || 8;
                const count = parseInt(countInput.value, 10) || 3;
                const unique = uniqueSelect.value; // 'on' 或 'off'
                // 边界限制
                const safeLength = Math.min(Math.max(length, 1), 999);
                const safeCount = Math.min(Math.max(count, 1), 50);
                lengthInput.value = safeLength;
                countInput.value = safeCount;
                // 更新统计
                statLength.textContent = `长度 ${safeLength}`;
                statCount.textContent = `数量 ${safeCount}`;
                const lines = [];
                for (let i = 0; i < safeCount; i++) {
                    lines.push(generateOneString(safeLength, unique));
                }
                // 填充输出 (用换行符分隔)
                outputArea.innerHTML = lines.join('<br>');
            }
            // 复制到剪贴板 (纯文本)
            function copyToClipboard() {
                const text = outputArea.innerText || outputArea.textContent;
                if (!text.trim()) {
                    alert('没有可复制的内容,请先生成汉字串。');
                    return;
                }
                navigator.clipboard.writeText(text).then(() => {
                    // 简单反馈
                    const originalText = copyBtn.innerText;
                    copyBtn.innerText = '✓ 已复制';
                    setTimeout(() => {
                        copyBtn.innerText = originalText;
                    }, 1800);
                }).catch(() => {
                    alert('复制失败,您可以选择文本手动复制。');
                });
            }
            // 自动更新绑定
            function handleAutoUpdate() {
                if (autoUpdateCheck.checked) {
                    generateAll();
                }
            }
            // 事件绑定
            generateBtn.addEventListener('click', generateAll);
            copyBtn.addEventListener('click', copyToClipboard);
            // 输入控件变化时自动更新 (如果自动更新开启)
            lengthInput.addEventListener('input', handleAutoUpdate);
            countInput.addEventListener('input', handleAutoUpdate);
            uniqueSelect.addEventListener('change', handleAutoUpdate);
            autoUpdateCheck.addEventListener('change', function() {
                if (this.checked) {
                    generateAll();
                }
            });
            // 初始化: 自动生成一次 (如果自动更新默认开启)
            window.addEventListener('DOMContentLoaded', function() {
                // 确保统计显示
                generateAll();
            });
        })();
    </script>
</body>
</html>

功能与操作说明

您可以通过调整参数,快速生成符合特定要求的汉字串。

  • 核心参数:您可以在面板中设置长度(每个字符串的字符数)和生成数量,开启“字符去重”可确保单个字符串内没有重复汉字。
  • 交互方式:点击 “生成” 按钮会立即根据当前参数生成结果,您也可以勾选 “自动更新”,这样每次调整参数时,结果都会自动刷新。
  • 结果处理:生成的汉字串会显示在输出区域,您可以使用 “复制” 按钮将全部结果(多行文本)一键复制到剪贴板。
  • 状态提示:输出区域上方会清晰显示当前设定的“长度”和“数量”,方便您核对。

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