【问题标题】:Convert a tokenized string into integers by using Javascript使用 Javascript 将标记化的字符串转换为整数
【发布时间】:2020-12-07 13:25:21
【问题描述】:

我已经看到了这个question,但是因为它在 python 中,我想问一个类似的问题。 如果不使用库,我将如何采用这种格式的标记化字符串数组:

[["hi","how","are", "you"], ["how", "are", "you", "doing"]] 

如果我有下面显示的字典,我将如何创建一个与标记化数组具有相同格式但不使用字符串的数组,我将使用一个整数来表示其在字典中的位置?

["how","hi","doing"]

所以输出应该是这样的:

[[2,1,0,0],[1,0,0,3]]

【问题讨论】:

    标签: javascript arrays encoding encode one-hot-encoding


    【解决方案1】:

    使用mapindexOf 方法

    arr = [
      ["hi", "how", "are", "you"],
      ["how", "are", "you", "doing"],
    ];
    
    // your input is array in javascript (not a dictionary)
    const keys = ["how", "hi", "doing"];
    
    const res = arr.map((arr) => arr.map((word) => keys.indexOf(word) + 1));
    
    console.log(res)

    【讨论】:

      【解决方案2】:

      我会先将第二个数组转换为一个对象,这样你就可以在恒定时间内进行查找:

      function translate(input, reference) {
          let map = Object.fromEntries(reference.map((ref, i) => [ref, i+1]));
          return input.map(phrase => phrase.map(word => map[word] || 0));
      }
      
      // Demo
      let res = translate([["hi","how","are","you"], ["how","are","you","doing"]], 
                          ["how","hi","doing"]);
      console.log(res);

      【讨论】:

        猜你喜欢
        • 2019-10-31
        • 2023-03-19
        • 1970-01-01
        • 2015-08-01
        • 2012-10-13
        • 2017-02-01
        • 1970-01-01
        • 2021-11-07
        • 1970-01-01
        相关资源
        最近更新 更多