是否有用于计算单词中音节数的javascript库?怎么算?
谢谢
编辑
感谢Sydenam和zozo提供有用的信息和可能的答案.
我在这个论坛上找到了Pesto的代码,但它是在Ruby中.其中一个简洁版本如下:
def new_count(word)
word.downcase!
return 1 if word.length <= 3
word.sub!(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '')
word.sub!(/^y/, '')
word.scan(/[aeiouy]{1,2}/).size
end
Run Code Online (Sandbox Code Playgroud)
这似乎很短但很复杂.你能把这个功能翻译成javascript吗?再次感谢你.
art*_*ker 34
翻译为javascript:
function new_count(word) {
word = word.toLowerCase(); //word.downcase!
if(word.length <= 3) { return 1; } //return 1 if word.length <= 3
word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, ''); //word.sub!(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '')
word = word.replace(/^y/, ''); //word.sub!(/^y/, '')
return word.match(/[aeiouy]{1,2}/g).length; //word.scan(/[aeiouy]{1,2}/).size
}
console.log(new_count('she'));
console.log(new_count('spain'))
console.log(new_count('softball'))
console.log(new_count('contagion'))Run Code Online (Sandbox Code Playgroud)
我可以看到这是一个旧帖子,但我偶然发现了这个功能并发现它很好用。
我想补充的一件事将提高音节帐户的准确性 - (据我所知)。
我注意到字符串“changes”仅显示为 1 个音节。
我删除es了(?:[^laeiouy]es|ed|[^laeiouy]e)$,现在是?:[^laeiouy]|ed|[^laeiouy]e)$.
这似乎为以“es”结尾的单词增加了额外的音节数。此外,为了简化事情,我将匹配的单词数组放入一个单独的变量中,这样您就可以在给出任何输出之前检查是否计算了任何音节:
var count = function(word)
{
word = word.toLowerCase();
word = word.replace(/(?:[^laeiouy]|ed|[^laeiouy]e)$/, '');
word = word.replace(/^y/, '');
//return word.match(/[aeiouy]{1,2}/g).length;
var syl = word.match(/[aeiouy]{1,2}/g);
console.log(syl);
if(syl)
{
//console.log(syl);
return syl.length;
}
}
Run Code Online (Sandbox Code Playgroud)
我发现这比必要的更方便。如果您在事件侦听器中运行的函数可能会在有任何要检查的单词之前触发,这将非常有用并可以防止任何错误,例如Cannot read property 'length' of null.
我只是想与其他可能发现并决定使用它的人分享我的发现。
您可以使用这个库pronouncingjs来使用 CMU 发音词典进行计算:
pronouncing.syllableCount(pronouncing.phonesForWord("adverse")[0])
2
Run Code Online (Sandbox Code Playgroud)
看这里:
abandon,3
abolish,3
absorb,2
accelerate,4
accept,2
access,2
accommodate,4
accompany,4
account,2
accumulate,4
accuse,2
ache,1
achieve,2
acknowledge,3
acquire,3
act,1
adapt,2
add,1
address,2
adhere,2
adjust,2
administer,4
admire,2
Run Code Online (Sandbox Code Playgroud)
好吧......你拿一本语法书并开始逐个字母地阅读字符串,如果其中一个规则匹配,那么你将+1 添加到计数器。由于不同语言的规则有所不同,我无法真正告诉您该怎么做。我为罗马尼亚语做的...但我怀疑它会对你有帮助。
| 归档时间: |
|
| 查看次数: |
5782 次 |
| 最近记录: |