本文目录导读:

Python 方案(推荐)
使用 pypinyin 库
# 安装:pip install pypinyin
from pypinyin import pinyin, Style
def text_to_pinyin(text, style=Style.TONE):
"""
转换文字为拼音
style:
Style.TONE - 带声调 (默认)
Style.NORMAL - 不带声调
Style.TONE2 - 数字声调
Style.INITIALS - 仅声母
Style.FINALS - 仅韵母
"""
result = pinyin(text, style=style)
# 转换为字符串
return ' '.join([item[0] for item in result])
# 示例
text = "你好世界"
print(text_to_pinyin(text)) # 输出: nǐ hǎo shì jiè
print(text_to_pinyin(text, Style.NORMAL)) # 输出: ni hao shi jie
更完整的转换函数
from pypinyin import pinyin, Style
import re
class PinyinConverter:
def __init__(self):
pass
def to_pinyin(self, text, tone=True, upper=False):
"""完整拼音转换"""
style = Style.TONE if tone else Style.NORMAL
result = []
for char in pinyin(text, style=style, heteronym=False):
p = char[0]
if upper:
p = p.upper()
result.append(p)
return ' '.join(result)
def to_pinyin_compact(self, text):
"""紧凑格式(无空格)"""
result = pinyin(text, style=Style.NORMAL)
return ''.join([item[0] for item in result])
def get_initials(self, text):
"""获取声母缩写"""
result = pinyin(text, style=Style.INITIALS)
return ''.join([item[0] for item in result])
# 使用示例
converter = PinyinConverter()
print(converter.to_pinyin("中国")) # zhōng guó
print(converter.to_pinyin("中国", upper=True)) # ZHŌNG GUÓ
print(converter.to_pinyin_compact("中国")) # zhongguo
print(converter.get_initials("中国")) # zhg
JavaScript 方案
使用 pinyin-pro 库
// 安装:npm install pinyin-pro
const { pinyin } = require('pinyin-pro');
// 基本用法
console.log(pinyin('汉语拼音')); // hàn yǔ pīn yīn
// 自定义选项
function textToPinyin(text, options = {}) {
const defaultOptions = {
toneType: 'symbol', // symbol: 带声调, none: 无声调, num: 数字声调
pattern: 'pinyin', // pinyin: 完整拼音, initials: 声母, finals: 韵母
type: 'string', // string: 字符串, array: 数组
uppercase: false, // 是否大写
separator: ' ' // 分隔符
};
const mergedOptions = { ...defaultOptions, ...options };
// 转换拼音
const result = pinyin(text, {
toneType: mergedOptions.toneType,
pattern: mergedOptions.pattern,
type: mergedOptions.type,
v: true
});
if (mergedOptions.uppercase && typeof result === 'string') {
return result.toUpperCase();
}
return result;
}
// 使用示例
console.log(textToPinyin('中文'));
console.log(textToPinyin('中文', { toneType: 'none' }));
console.log(textToPinyin('中文', { uppercase: true }));
纯前端使用
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/pinyin-pro@3.18.2/dist/pinyin-pro.js"></script>
</head>
<body>
<input id="input" placeholder="输入文字" />
<button onclick="convert()">转换拼音</button>
<div id="output"></div>
<script>
function convert() {
const text = document.getElementById('input').value;
const result = pinyinPro.pinyin(text, {
toneType: 'symbol'
});
document.getElementById('output').textContent = result;
}
</script>
</body>
</html>
Shell 脚本方案
使用 xclip 和 python(Linux)
#!/bin/bash
# 保存为 pinyin.sh
convert_to_pinyin() {
local text="$1"
python3 -c "
from pypinyin import pinyin, Style
text = '$text'
result = pinyin(text, style=Style.TONE)
print(' '.join([item[0] for item in result]))
"
}
# 从剪贴板读取并转换
if [ -n "$1" ]; then
convert_to_pinyin "$1"
else
# 读取标准输入
while read line; do
convert_to_pinyin "$line"
done
fi
批处理方案
import os
from pypinyin import pinyin, Style
def batch_convert_file(input_file, output_file):
"""批量转换文件中的文本"""
with open(input_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
with open(output_file, 'w', encoding='utf-8') as f:
for line in lines:
line = line.strip()
if line:
result = pinyin(line, style=Style.TONE)
pinyin_line = ' '.join([item[0] for item in result])
f.write(f"{line} -> {pinyin_line}\n")
else:
f.write("\n")
# 使用
batch_convert_file('input.txt', 'output.txt')
安装说明
Python
pip install pypinyin
JavaScript (Node.js)
npm install pinyin-pro
示例输出
| 输入 | 拼音输出 |
|---|---|
| 你好 | nǐ hǎo |
| 中国 | zhōng guó |
| 学习 | xué xí |
| 北京 | běi jīng |
这些脚本简单易用,可以根据需要选择合适的方案,最常用的是 Python 的 pypinyin 库,功能完整且易用。