node.js - 函数错误在离子角度中使用自然nodejs库
问题描述
呃,我目前正在开发一个 Ionic 应用程序(最新版本类似于 6)。我想使用 TFIDF 和余弦相似度创建一些基于内容的推荐系统。
由于有库可以帮助计算自然的 TFIDF,所以我去在我的项目中包含自然的 nodejs 库。我确实在我的项目中安装了自然库。像这样
npm install natural
然后我在我的.ts
文件中声明/导入库,--我只需要使用库中包含的 TFIDF,所以我声明它是这样的:
const natTfIdf = require('natural/lib/natural/tfidf')
然后在页面类的某个地方我使用这个:
const TfIdf = natTfIdf.TfIdf,
tfidf = new TfIdf();
然后我开始在文件中的某个函数中使用它.ts
:
//collect all terms after tokenize and stemming
var termsAll = [...corpus[13], ...corpus[14], ...corpus[15], ...corpus[16]];
//show unique terms only
var terms = termsAll.filter(unique);
//I want to test some of the data
//inserted to tfidf
for (var i = 13; i < 17; i++) {
tfidf.addDocument(corpus[i]);
console.log(corpus[i]);
}
terms.forEach(item => {
console.log(item);
tfidf.tfidfs(item, function (i, measure) {
if (i == 2) {
console.log('document #Q' + ' is ' + measure);
} else {
console.log('document #' + (i + 1) + ' is ' + measure);
}
});
});
问题出tfidf.js
在图书馆内部,如下所示:
TfIdf.prototype.tfidf = function (terms, d) {
const _this = this;
return terms.reduce(function (value, term) {
let idf = _this.idf(term);
idf = idf === Infinity ? 0 : idf;
return value + (tf(term, _this.documents[d]) * idf);
}, 0.0);
};
TfIdf.prototype.tfidfs = function (terms, callback) {
const tfidfs = new Array(this.documents.length)
for (let i = 0; i < this.documents.length; i++) {
tfidfs[i] = this.tfidf(terms, i)
if (callback) { callback(i, tfidfs[i], this.documents[i].__key) }
}
return tfidfs
}
我得到的错误是这样的:
ERROR TypeError: terms.reduce is not a function
at TfIdf.tfidf (tfidf.js:167)
at TfIdf.tfidfs (tfidf.js:197)
at DetailPage.calculateTFIDF (detail.page.ts:143)
at DetailPage.getBagOfWords (detail.page.ts:163)
at SafeSubscriber._next (detail.page.ts:182)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
at SafeSubscriber.next (Subscriber.js:122)
at Subscriber._next (Subscriber.js:72)
at Subscriber.next (Subscriber.js:49)
at MapSubscriber._next (map.js:35)
我想要的结果是在我的浏览器控制台中显示此日志ionic serve
:
node --------------------------------
document #0 is 0
document #1 is 0
document #2 is 3.347952867143343
document #3 is 1.6739764335716716
document #4 is 0
ruby --------------------------------
document #0 is 0
document #1 is 1.6739764335716716
document #2 is 1.6739764335716716
document #3 is 0
document #4 is 0
任何想法来解决这个问题或以离子角度使用这个库的正确方法?
谢谢
解决方案
推荐阅读
- javascript - 如何将 h264 编码的 MediaRecorder 流传递给 Chrome 中的 MediaSource?
- javascript - 检查是否没有数据要使用 AJAX 发送
- python - 使用运算符将 c++ 代码转换为 python?
- python - Python继承:使用父方法打印继承变量时出现属性错误
- api - 如何使用 gcloud 在 GCP 中启用 API 服务进行故障排除
- android - Kotlin 数组中的所有项始终包含最后一项
- django - Django admin TabularInline “502 Bad Gateway” nginx 过早关闭连接
- shell - 确定在 Linux 中使用给定可执行文件启动的所有进程
- amazon-web-services - 如何使用 Terraform 0.11 访问其中包含地图的列表列表?
- google-api-dotnet-client - 由 Google.Apis.Storage.v1 build 1.45.0.1957 引起的 MSBuild 警告