gpt4 book ai didi

javascript - 使用函数式 javascript 和 ramda 查找和替换

转载 作者:行者123 更新时间:2023-12-03 05:26:50 24 4
gpt4 key购买 nike

我正在研究 ramda,并有以下问题 Ramda REPL :

const R = require('ramda')
//const original = require('./test/fixtures/original.json')
const original = {
speakers: {
name: 'Author',
words: [
{ duration: '0.360000', name: 'Arthur', time: '0.660000', paragraph: 'p0-0' },
{ duration: '0.150000', name: 'the', time: '1.020000', paragraph: 'p0-0' },
{ duration: '0.380000', name: 'rat', time: '1.170000', paragraph: 'p0-0' },
{ duration: '0.770000', name: '.', time: '1.550000', paragraph: 'p0-0' },
{ duration: '0.360000', name: 'Arthur', time: '89.820000', paragraph: 'p1-0' },
{ duration: '0.390000', name: 'stood', time: '90.180000', paragraph: 'p1-0' },
{ duration: '0.090000', name: 'and', time: '90.570000', paragraph: 'p1-0' }
]
}
}

const words = R.lensPath(['speakers', 'words'])
const wordsList = R.view(words, original)
const result = [...wordsList.reduce((hash, { duration, time, name, paragraph }) => {
const current = hash.get(paragraph) || { paragraph, words: [] };

current.words.push({ duration, time, name });

return hash.set(paragraph, current);
}, new Map).values()];

console.log(result);

如何使用 groupBy 来按段落分组而不是上述方法?

根据这个结果,如何通过按时间顺序对所有单词进行排序并仅返回匹配的段落来查找可以包含一个或多个项目的字符串?

search_criteria = 'Arthur stood';

results = [
{ para: 'p1-0',
words: [
{ 'name': 'Arthur', 'time': 89.820000},
{ 'name': 'stood', 'time': 90.180000}
}
]

如何用 replace = 'Arthuro Stop' 替换这些项目

非常感谢任何建议。

最佳答案

解决 Ramda 第一个问题的方法如下:

pipe(
view(lensPath(['speakers', 'words'])), // original.speakers.words (null-safe)
groupBy(prop('paragraph')), // object with keys of para name, values of list of matching records
map(map(dissoc('paragraph'))), // removing unneeded para from records
toPairs, // {p1: [...words1], p2: [...words2]} => [[p1, [...words1]], [p2, [...words2]]]
map(zipObj(['paragraph', 'words'])) // expected output structure
)(original)

您具体询问了groupBy。在 groupBy(prop('paragraph')) 子句之后,数据如下所示:

{
"p0-0": [
{duration: "0.360000", name: "Arthur", paragraph: "p0-0", time: "0.660000"},
{duration: "0.150000", name: "the", paragraph: "p0-0", time: "1.020000"},
{duration: "0.380000", name: "rat", paragraph: "p0-0", time: "1.170000"},
{duration: "0.770000", name: ".", paragraph: "p0-0", time: "1.550000"}
],
"p1-0": [
{duration: "0.360000", name: "Arthur", paragraph: "p1-0", time: "89.820000"},
{duration: "0.390000", name: "stood", paragraph: "p1-0", time: "90.180000"},
{duration: "0.090000", name: "and", paragraph: "p1-0", time: "90.570000"}
]
}

剩下的只是为了获得您正在寻找的输出结构。

您可以在Ramda REPL中看到结果。 (如果您注释掉管道中后面的行,您可以看到任何中间结果。)

对于您问题的后半部分,我建议您打开一个新主题,展示您迄今为止所做的尝试。

关于javascript - 使用函数式 javascript 和 ramda 查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41111994/

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