如何计算谷歌文档中"I"、"You"、"We"的数量?



这是一个简单的方法。如果您有任何更令人惊叹的解决方案。不客气。请随意使用。它适用于我的文档。

故事从我和女朋友的一场战斗开始,就像我给她写的一封信一样。即兴发挥的良好平衡给我留下了深刻的印象;I"你",并在";我们";,我不能接受她的批评。

function myFunction_Count_YnInW() {

var space = " ";
var text = DocumentApp.getActiveDocument().getBody().getText();
var words = text.replace(/s+/g, space).split(space);
var theCount_I = 0;
var theCount_Y = 0;
var theCount_W = 0;
for(var i=0;i<words.length;i++){
var theWord = words.slice(i,i+1).toString().toLowerCase();
if(theWord=="i"){
theCount_I++;
//    }else if(theWord=="me"){
//        theCount_I++;
}else if(theWord=="you"){
theCount_Y++;
}else if(theWord=="we"){
theCount_W++;
}else if(theWord=="us"){
theCount_W++;
}
} 
var message = "Here are the results : n" 
+ "Number of words = "+ words.length + " n"
+ "Number of 'I'= "+ theCount_I + " n"
+ "Number of 'You'= "+ theCount_Y + " n"
+ "Number of 'Us'= "+ theCount_W; 
Logger.log(message);
//DocumentApp.getUi().alert(message);
return message;

}

因此,我建议优化脚本的方法是在结果中添加百分比。

function myFunction_Count_YnInW() {

var space = " ";
var text = DocumentApp.getActiveDocument().getBody().getText();
var words = text.replace(/s+/g, space).split(space);
var theCount_I = 0;
var theCount_Y = 0;
var theCount_W = 0;
var wordsCount = words.length;
for(var i=0;i<wordsCount;i++){
var theWord = words.slice(i,i+1).toString().toLowerCase();
if(theWord=="i"){
theCount_I++;
//    }else if(theWord=="me"){
//        theCount_I++;
}else if(theWord=="you"){
theCount_Y++;
}else if(theWord=="we"){
theCount_W++;
}else if(theWord=="us"){
theCount_W++;
}
} 
var message = "Here are the results : n" 
+ "Number of words = "+ wordsCount + " n"
+ "Number of 'I'= "+ theCount_I + " (" + (theCount_I/wordsCount*100) + ") n"
+ "Number of 'You'= "+ theCount_Y+ " (" + (theCount_Y/wordsCount*100)  +") n"
+ "Number of 'Us'= "+ theCount_W + " ("+ (theCount_W/wordsCount*100) + ")"; 
Logger.log(message);
//DocumentApp.getUi().alert(message);
return message;
}

结果如下:

字数=283

"I"的数量=16(5.6537102473498235(

"您"的数量=18(6.36042402826855(

"我们"的数量=6(2.1201413427561837(

相关内容

最新更新