Files
wushu/lib/views/home/care/pinyin_helper.dart
2026-04-02 22:30:49 +08:00

80 lines
2.0 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/// 时间: 2026-04-02
/// 功能: 拼音处理辅助类
/// 介绍: 使用pinyin库为汉字生成带音调的拼音
/// 最新变化: 2026-04-02 修正API使用方式避免递归调用
import 'package:pinyin/pinyin.dart' as pinyin;
class PinyinHelper {
/// 将汉字转换为带音调的拼音
static String convertToPinyin(String text) {
if (text.isEmpty) return '';
try {
// 使用pinyin库将汉字转换为拼音
return pinyin.PinyinHelper.getPinyin(
text,
separator: ' ',
format: pinyin.PinyinFormat.WITH_TONE_MARK,
);
} catch (e) {
// 无法转换时返回空字符串
return '';
}
}
/// 为诗词内容生成拼音
static String generatePoetryPinyin(String content) {
if (content.isEmpty) return '';
// 按行分割诗词
List<String> lines = content.split('\n');
List<String> pinyinLines = [];
// 为每行生成拼音
for (String line in lines) {
if (line.trim().isNotEmpty) {
String linePinyin = convertToPinyin(line);
pinyinLines.add(linePinyin);
} else {
pinyinLines.add('');
}
}
return pinyinLines.join('\n');
}
/// 将字符串转换为每个汉字及其对应的拼音的列表
static List<Map<String, String>> convertToCharPinyinList(String text) {
if (text.isEmpty) return [];
List<Map<String, String>> result = [];
try {
// 为每个字符生成拼音
for (int i = 0; i < text.length; i++) {
String char = text[i];
String charPinyin = '';
try {
charPinyin = pinyin.PinyinHelper.getPinyin(
char,
separator: ' ',
format: pinyin.PinyinFormat.WITH_TONE_MARK,
);
} catch (e) {
// 无法转换时使用空字符串
charPinyin = '';
}
result.add({'char': char, 'pinyin': charPinyin});
}
} catch (e) {
// 发生错误时返回空列表
return [];
}
return result;
}
}