复制 import re
# 成语接龙核心:检查尾字与首字是否同音(忽略声调)
# 使用拼音库 pypinyin 实现
from pypinyin import lazy_pinyin, Style
def get_last_char_pinyin(word: str) -> str:
"""获取成语最后一个字的拼音(无声调)"""
if len(word) < 2:
return ""
last_char = word[-1]
# 取无声调拼音
pinyin = lazy_pinyin(last_char, style=Style.TONE3, neutral_tone_with_five=True)
# 去掉声调数字
return re.sub(r'[0-5]', '', pinyin[0])
def can_chain(prev: str, next_: str) -> bool:
"""判断 next_ 能否接在 prev 后面(同音接龙)"""
if len(prev) < 2 or len(next_) < 2:
return False
prev_tail = get_last_char_pinyin(prev)
next_head = get_last_char_pinyin(next_[:1]) # 取首字拼音
return prev_tail == next_head
# 示例
print(can_chain("马到成功", "功德无量")) # True(功=gong, 功=gong)
print(can_chain("马到成功", "马不停蹄")) # False(功=gong, 马=ma)复制 package main
import (
"fmt"
"regexp"
"strings"
"github.com/mozillazg/go-pinyin"
)
// getLastCharPinyin 获取成语最后一个字的无声调拼音
func getLastCharPinyin(word string) string {
if len([]rune(word)) < 2 {
return ""
}
runes := []rune(word)
lastChar := string(runes[len(runes)-1])
// 获取拼音(带声调数字)
a := pinyin.NewArgs()
a.Style = pinyin.Tone3
result := pinyin.Pinyin(lastChar, a)
if len(result) == 0 {
return ""
}
// 去掉声调数字
re := regexp.MustCompile(`[0-5]`)
return re.ReplaceAllString(result[0][0], "")
}
// canChain 判断两个成语能否接龙(同音接龙)
func canChain(prev, next string) bool {
if len([]rune(prev)) < 2 || len([]rune(next)) < 2 {
return false
}
prevTail := getLastCharPinyin(prev)
nextHead := getLastCharPinyin(string([]rune(next)[0]))
return strings.EqualFold(prevTail, nextHead)
}
func main() {
fmt.Println(canChain("马到成功", "功德无量")) // true
fmt.Println(canChain("马到成功", "马不停蹄")) // false
}复制 // 成语接龙:使用 pinyin 库(npm install pinyin)
const pinyin = require('pinyin');
/**
* 获取成语最后一个字的无声调拼音
*/
function getLastCharPinyin(word) {
if (word.length < 2) return '';
const lastChar = word[word.length - 1];
// 取拼音数组,style: 0 表示无声调
const result = pinyin(lastChar, { style: pinyin.STYLE_NORMAL });
return result[0] || '';
}
/**
* 判断两个成语能否接龙(同音接龙)
*/
function canChain(prev, next) {
if (prev.length < 2 || next.length < 2) return false;
const prevTail = getLastCharPinyin(prev);
const nextHead = getLastCharPinyin(next[0]);
return prevTail === nextHead;
}
// 示例
console.log(canChain('马到成功', '功德无量')); // true
console.log(canChain('马到成功', '马不停蹄')); // false