我正在研究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 stopped'
替换这些项目?
非常感谢任何建议。
答案 0 :(得分:1)
解决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 中查看结果。 (如果您在管道中注释掉后面的行,则可以看到任何中间结果。)
对于你问题的后半部分,我建议你打开一个新主题,展示你到目前为止所尝试的内容。