javascript 生成自然语言

2022-07-22 20:18
24
0
添加收藏

简介  这篇文章主要介绍了javascript 生成自然语言以及相关的经验技巧,文章约1533字,浏览量3382,点赞数52, 强烈推荐!

// sample generating grammar for sentences.

function randomSample(arr) {
return arr[Math.floor(Math.random()*arr.length)];
}

function genStatement(gram) {
var statement = [];
var path = randomSample(gram.rule.start);
while(path != "end") {
 statement.push(randomSample(gram.vocab[path]));
 path = randomSample(gram.rule[path]);
}
return statement.join(" ");
}

// sample model of grammar
var grammar = {
// rule contains the pathways
"rule":{
 "start":["det", "desc", "noun"],
 "noun":["end"],
 "det":["desc", "noun"],
 "desc":["noun"]
},
"vocab":{
 "det":["the", "this", "that", "one"],
 "desc":["red", "blue", "green", "yellow", "purple", "pink", "round", "big", "tall", "long", "small", "black", "white", "brown"],
 "noun":["leaf", "branch", "toy", "car", "bus", "train", "taxi", "house"]
}
};

for(var i =0; i< 300; i++) console.log(genStatement(grammar));

以上就是本文的全部内容,希望对大家的学习有所帮助,本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 原文地址:https://www.it1352.com/OnLineCodeSnippets/TagList?pageindex=848&pagesize=10&tag=javascript

全部评论