gpt4 book ai didi

javascript - 计算示例文本的 2 个给定单词之间的距离

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:21:17 25 4
gpt4 key购买 nike

我正在寻找一种方法来输出距离(空格分隔的单词的数量)以在 2 个给定的单词之间进行控制。考虑以下 .txt 输入:

[SEP] Today I went to school for the first time . [/SEP] [SEP] Everyone was excited to see me ! [/SEP]

我现在需要获取 [SEP][/SEP] 之间的距离,在本例中为 9 和 6。

您可能猜到,真正的 .txt 输入要长得多。

更新:到目前为止我的方法(拆分成数组):

var text = "[SEP] Today I went to school for the first time . [/SEP] [SEP] Everyone was excited to see me ! [/SEP]";
var textArray = text.split(/\[SEP\]|\[\/SEP\]/);

更新:匹配评论中提供的正则表达式

var text = "[SEP] Today I went to school for the first time . [/SEP] [SEP] Everyone was excited to see me ! [/SEP]";
var matchText = text.match("\[[A-Z]+\]([^[]+)\[\/[A-Z]+\]");

更新:使用 .exec()

var myText = \[[A-Z]+\]([^[]+)\[\/[A-Z]+\].exec('[SEP] Today I went to school for the first time . [/SEP] [SEP] Everyone was excited to see me ! [/SEP]')

最佳答案

尝试使用 split 拆分文本。这将提供 SEP 之间的单词列表。

"[SEP]this is [/SEP] an interesting [SEP] thing[/SEP]".split(/\[SEP\]|\[\/SEP\]/)

之后,您可以使用

确定每个组的大小
words.length - words.replace(/ /g,'').length

完整解决方案:

var wordGroups = "[SEP]this is [/SEP] an interesting [SEP] thing[/SEP]".split(/\[SEP\]|\[\/SEP\]/)
wordGroups.forEach(function(wordGroup) {
wordGroup = wordGroup.trim()
if (wordGroup.length == 0 ) {
return
}
var nrOfWords = wordGroup.length - wordGroup.replace(/ /g,'').length + 1
console.log("\"" + wordGroup + "\" has " + nrOfWords + " words")
})

关于javascript - 计算示例文本的 2 个给定单词之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33605473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com