如何在Javascript中混合使用英语和汉语进行字数统计
How to do word counts for a mixture of English and Chinese in Javascript
我想计算一段包含英语和汉语的文章中的字数。对于英语来说,这很简单。每个单词都是一个单词。对于汉语,我们把每个字符都看作一个单词。因此香港人这里有三个字。
例如,"我是香港人"的字数应该是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>
现在,脚本正确地计算了中英文混合体中的单词数量。。。。享受
相关文章:
- Java-彩票统计解析器
- 统计ajax返回数据中的html元素
- 如何使用jQuery对多个文本区域进行字数统计
- 关于使用image.src进行统计的问题
- 使用Javascript从Strobe Media Playback获取统计信息
- Javascript统计计算器
- 更改阿尔戈利亚即时搜索.js统计模板
- 时间序列统计(如相关性、傅里叶变换)
- JSnice如何进行统计重命名,重命名Javascript变量
- 统计网站中点击次数最多的视频
- 随机数生成器,what'我的方法/统计数据有问题吗?[JS]
- Javascript;Cookie:统计所有页面的访问量
- 如何在Javascript中混合使用英语和汉语进行字数统计
- jQuery统计背景图像的纵横比并更改元素的填充值
- 在网站上显示该网站的GA统计数据
- 如何统计复选框的复选值总数
- 相关视频与部分内容详细信息和统计-Youtube API V3
- 我怎么知道MYSQL统计中哪个字段不匹配
- 从 SQL 数据库自动更新统计信息
- j查询“keyup”在检查“字数统计”时崩溃页面