我有这个字符串:

Table {is {red|blue|orange|white|green-{yellow|black}} |has {{twenty|thirty}two|{{two hundered and |three hundered and }fourty |fifty }three|four} legs} and is placed { in corner | in the middle } of office and {printer|phone} is {{gray-|}black|white}.


我想要一些我可以使用的数据结构,您能提出一些建议吗?

这是我的尝试:

var matches = $scope.fileContent.match(/{([^}]+)}/g);

for (var i = 0; i < matches.length; i++) {
   console.log(matches[i]);
}


我想要随机句子

可能的结果:

 - Table is blue and is placed in corner of office and printer is black.
 - Table has three hundered and fourty three legs and is placed in the middle of office and phone is gray-black.

最佳答案

这种句子结构的语法是:

SENTENCE     := PARTIAL optional SENTENCE
PARTIAL      := TEXT or BRANCH
BRANCH       := '{' SENTENCE ALTERNATIVES '}'
ALTERNATIVES := '|' SENTENCE optional ALTERNATIVES


也许我可以在不同阶段使用更清晰的名称,但是您明白了。您可以使用该语法规则来分解您的任何句子。解析后,您将获得树状结构的句子。

将字符串解析为该树结构后,就可以遍历它,并随机选择要采用的分支。 JavaScript中的示例:

var string = "A table {is {red|blue|green}|has {four|five} legs}"
var index = 0
var root = new Node()
var current = root

function Node() {
    this.text = ""
    this.options = []
    this.next = null
}

Node.prototype.toString = function(){
    var string = this.text;
    if (this.options.length > 0) {
        var rnd = Math.floor(Math.random() * this.options.length)
        string += this.options[rnd].toString()
    }
    if (this.next != null)
        string += this.next.toString()
    return string
}

function parse() {
    text()
    if (index == string.length)
        return

    if (string[index] == "{") {
        index++
        options()
        var next = new Node()
        current.next = next
        current = next
        parse()
    }
}

function options() {
    var parent = current
    while(true) {
        current = new Node()
        parent.options.push(current)
        parse()
        index++
        if (string[index - 1] != '|')
            break
    }
    current = new Node()
    parent.next = current
}

function text() {
    while (index < string.length && "{|}".indexOf(string[index]) == -1) {
        current.text += string[index]
        index++
    }
}

parse()
alert(root.toString())


请注意-这不能处理以下字符串:


“一些文字{没有右花括号”
“一个意外的|管道符号”
“一个意外的}大括号”


我会让你自己添加。

07-24 09:37
查看更多