【问题标题】:Retrieve attributes from plain written text从纯文本中检索属性
【发布时间】:2012-03-13 23:56:13
【问题描述】:

假设我们有这个文本

这个 85 公斤的家伙跑了 10 英里,然后我们可以看出他只是印刷和排版行业的虚拟文本,所有这一切都在 2 小时内完成

我们想要捕捉:

  1. 85 公斤

  2. 10 英里

  3. 2 小时

我试图想出一个可以检索 som 属性(corse 已知的属性)的函数

假设我们要检测:

属性:[数量] [计量]

我们的mesures 是:

[miles, seconds, hours, minutes, times, kilos]

所以我想在空格中分解文本,检查数组中的单词是否(测量),如果前一个单词是数字,那么我有一个属性:D

(这是一种伪/javascript代码)

function get_mesure_attrs(txt){
     var text = txt.split(' ');
     for (i=1;i<=text.length;i++{    /*Note i begin with i=1 cause the first word would never be a mesure of a desired atribute */
         if(text[i] is in_array(mesures){
            if(is_number(text[i-1]){
                console.log('Atribute: '+text[i-1]+' '+text[i]);
            }
     }
}

我对相关的关联数组没有足够的了解,所以我想知道是否有人可以给我一个提示,

非常感谢

【问题讨论】:

  • 你的方法是正确的..那么为什么不先尝试呢? SO上没有多少人喜欢回答没有尝试解决问题的问题。

标签: javascript arrays parsing tags textarea


【解决方案1】:
var str= "The 85 kilos guy rant 10 miles and then we can se he is simply dummy text of the printing and typesetting industry and all of this in 2 hours 1 kilo",
measures = "mile|second|hour|minute|time|kilo";
function getMeasureAttrs(txt) {
  var re = RegExp( "\\b(\\d+)\\s(("+ measures +")s?)","g" );
  var attrs = [];
  txt.replace( re, function  ( $, $1, $2 ) {
    attrs.push ([ $1, $2 ] );
  })
  return attrs;
}
console.log(  getMeasureAttrs( str ) ); // [["85", "kilos"], ["10", "miles"], ["2", "hours"],["1","kilo"]]

提前申请

【讨论】:

  • 嘿!这看起来很棒!我们如何改变它来处理单数和复数? (一秒,两秒)
  • var re = RegExp("\\b(\\d+)\\s("+measures +")s?","g");
  • 嘿,谢谢你的回复!但你确定吗?我输入 1 公斤,它不推它...
【解决方案2】:

我建议使用正则表达式:

function getMeasureAttrs(txt) {
  var re = /(\d+)\s+(miles|seconds|hours|minutes|times|kilos)/g;
  var match;
  while (match = re.exec(txt)) {
    console.log('Attribute: ' + match[1] + ' ' + match[2]);
  }
}

正则表达式中的两个括号部分是匹配的。第一个(\d+)是一个整数,第二个是你指定的单位列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2011-08-01
    • 2012-05-12
    • 2016-11-03
    • 2011-01-18
    • 1970-01-01
    相关资源
    最近更新 更多