Google Apps脚本中有没有一个方法可以从Google文档中返回字数统计?
假设我正在写一份对字数有特殊限制的报告。它非常精确,它恰好说明了1.8k - 2k个单词(是的,这不只是一个例子,而是许多……)
在Microsoft Office Word中,页面底部有一个方便的状态栏,它会自动为我更新字数统计,所以我尝试使用Google Apps脚本创建一个状态栏。
编写一个从当前文档中取出整个文本,然后一遍又一遍地计算单词的函数,对我来说就像是胡说八道。这是完全低效的,它使CPU毫无意义地运行,但我在Docs参考中找不到用于字数统计的函数。
Ctr+Shift+C打开一个包含它的弹出窗口,这意味着一个返回谷歌文档总字数的函数肯定存在……
但是我找不到它!叹息..。我花了几个小时翻遍了谷歌,但我就是找不到,请帮帮忙!
发布于 2015-10-26 14:42:01
写了一小段可能会有帮助的片段。
function myFunction() {
var space = " ";
var text = DocumentApp.getActiveDocument().getBody().getText();
var words = text.replace(/\s+/g, space).split(space);
Logger.log(words.length);
}发布于 2020-01-20 22:21:32
我知道该请求是为了一个内置函数,我也在寻找它,但在文档中找不到。我不得不使用轮询。我从一个像Amit的脚本开始,但发现我从来没有匹配过Google的字数。这是我为了让它工作而不得不做的事情。我知道这样做效率不高,但现在大部分时间都能与google文档的数量相匹配。我要做的是首先清理/重建字符串,然后再计算它。
function countWords() {
var s = DocumentApp.getActiveDocument().getBody().getText();
//this function kept returning "1" when the doc was blank
//so this is how I stopped having it return 1.
if (s.length === 0)
return 0;
//A simple \n replacement didn't work, neither did \s not sure why
s = s.replace(/\r\n|\r|\n/g, " ");
//In cases where you have "...last word.First word..."
//it doesn't count the two words around the period.
//so I replace all punctuation with a space
var punctuationless = s.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()"?“”]/g," ");
//Finally, trim it down to single spaces (not sure this even matters)
var finalString = punctuationless.replace(/\s{2,}/g," ");
//Actually count it
var count = finalString.trim().split(/\s+/).length;
return count;
}发布于 2021-08-04 04:30:33
我认为这个函数可能涵盖了大多数使用英文字符的字数统计。如果我漏掉了什么,请评论。
function testTheFunction(){
var myDoc = DocumentApp.openByUrl('https://docs.google.com/document/d/?????/edit');
Logger.log(countWordsInDocument(myDoc));
}
function countWordsInDocument(theDoc){
var theText = theDoc.getBody().getText();
var theRegex = new RegExp("[A-Za-z]") // or include other ranges for other languages or numbers
var wordStarted = false;
var theCount = 0;
for(var i=0;i<theText.length;i++){
var theLetter = theText.slice(i,i+1);
if(theRegex.test(theLetter)){
if(!wordStarted){
wordStarted=true;
theCount++;
}
}else if(wordStarted){
wordStarted=false;
}
}
return theCount;
}https://stackoverflow.com/questions/33338667
复制相似问题