ReactJS 标记 rasa nlu 实体文本突出显示



我正在开发一个简单的反应应用程序来显示rasa HTTP api结果数据,我想在句子中标记实体。我的代码适用于 1 个单词的实体,但中断了 2 个单词(仅突出显示第一个单词(

这就是我正在做的

  const [colors, setColors] = useState([
    "salmon",
    "primary",
    "purple",
    "orange"
  ]);
  const tagSentence = () => {
    let sentence = props.data.text;
    const entities = props.data.entities;
    entities.map((e, eIndex) => {
      sentence = sentence.replace(e.value, `<${eIndex}>${e.value}`);
    });
    return sentence.split(" ");
  };

          <Typography variant="h5" component="h2">
            {props.data.entities.map(t => {
              if (t.value.includes("<")) {
                return (
                  <Chip
                    key={t.value}
                    label={t.slice(3, t.length)}
                    color="primary"
                    style={{ backgroundColor: colors[t.slice(1, 2)] }}
                  />
                );
              } else {
                return ` ${t} `;
              }
            })}
          </Typography>

实体对象具有单词开头和结尾的索引,但我不知道如何使用它。

例句:

彼得是我最好的朋友

{
"text" : "peter is my best friend"
"entities" : [{"entity": "PERSON", "value": "peter", "start": 1, "end": 5...}]
}

编辑:

以此结束,现在正在寻找如何在 JS 中包含整个单词

          <Typography variant="h5" component="h2">
            {props.data.text.split(" ").map((s, sIndex) => {
              return props.data.entities.map((e, eIndex) => {
                if (e.value.includes(s)) {
                  return (
                    <Chip
                      key={s}
                      label={s}
                      style={{ backgroundColor: colors[sIndex] }}
                      color="primary"
                    />
                  );
                } else {
                  return ` ${s} `;
                }
              });
            })}
          </Typography>

我终于用 https://github.com/iansinnott/react-string-replace 轻松地用组件替换字符串,就像一个魅力。

  const tagSentence = () => {
    let sentence = props.data.text;
    props.data.entities.forEach((e, eIndex) => {
      sentence = reactStringReplace(sentence, e.value, (match, i) => (
        <Chip
          key={i}
          label={match}
          style={{ backgroundColor: colors[eIndex] }}
          color="primary"
        />
      ));
    });
    return sentence;
  };

最新更新