如何在Javascript中混合使用英语和汉语进行字数统计

How to do word counts for a mixture of English and Chinese in Javascript

本文关键字:汉语 统计 英语 Javascript 混合      更新时间:2024-04-03

我想计算一段包含英语和汉语的文章中的字数。对于英语来说,这很简单。每个单词都是一个单词。对于汉语,我们把每个字符都看作一个单词。因此香港人这里有三个字。

例如,"我是香港人"的字数应该是6。

知道我如何在Javascript/jQuery中计数吗?

谢谢!

尝试这样的正则表达式:

/['u00ff-'uffff]|'S+/g

例如,"I am a 香港人".match(/['u00ff-'uffff]|'S+/g)给出:

["I", "am", "a", "香", "港", "人"]

然后,您可以检查得到的数组的长度。

正则表达式的'u00ff-'uffff部分是unicode字符范围;你可能想把它缩小到你想算作单词的字符。例如,CJK Unified将是'u4e00-'u9fcc

function countWords(str) {
    var matches = str.match(/['u00ff-'uffff]|'S+/g);
    return matches ? matches.length : 0;
}

它不能是6,因为当您计算字符串的长度时,它也包括空格。所以,

var d = "I am a 香港人";
d.length //returns 10
d.replace(/'s+/g, "").length  //returns 7, excluding spaces

仅供参考:您的网站应该正确编码。

我想我找到了你需要的。"我是香港人"这包含重复两次的a。因此在@PSL的答案的帮助下,我找到了一种方法。

var d = "I am a 香港人";
var uniqueList=d.replace(/'s+/g, '').split('').filter(function(item,i,allItems){
    return i==allItems.indexOf(item);
}).join('');
console.log(uniqueList.length);  //returns 6

JSFiddle

当你评论时,我假设你的句子是"我是香 港 人"每个单词之间的空格。现在我修改了代码

var d = "I am a 香 港 人";
var uniqueList=d.split(' ').filter(function(item,i,allItems){
    return i==allItems.indexOf(item);
});
console.log(uniqueList.length);  //returns 6

JSFiddle

我试过这个脚本,但它有时会错误地计算字数。例如,有些人会键入"香港人计算都不錯的",但脚本会将其计算为4个单词(使用以下脚本)。

<script>
var str = "香港人computing都不錯的";
  var matches = str.match(/['u00ff-'uffff]|'S+/g);
    x= matches ? matches.length : 0;
    alert(x)
</script>

为了解决这个问题,我将代码更改为:

<script>
var str="香港人computing都不錯的";
/// fix problem in special characters such as middle-dot, etc.   
str= str.replace(/['u007F-'u00FE]/g,' ');
/// make a duplicate first...
var str1=str;
var str2=str;
/// the following remove all chinese characters and then count the number of english characters in the string
str1=str1.replace(/[^!-~'d's]+/gi,' ')
/// the following remove all english characters and then count the number of chinese characters in the string
str2=str2.replace(/[!-~'d's]+/gi,'')

var matches1 = str1.match(/['u00ff-'uffff]|'S+/g);
var matches2 = str2.match(/['u00ff-'uffff]|'S+/g);

count1= matches1 ? matches1.length : 0;
count2= matches2 ? matches2.length : 0;
/// return the total of the mixture
var lvar1= (count1+count2);
alert(lvar1);
</script>

现在,脚本正确地计算了中英文混合体中的单词数量。。。。享受