繁体   English   中英

标记词的正则表达式

[英]Regular expression on tagged words

给定一个字符串,表示这样的句子,然后使用 OpenNLP 标记该字符串。

String sentence = "His plays remain highly popular, and are constantly studied.";

我在下面得到这个。 我的问题是我怎么知道对它应用正则表达式来过滤掉标签? 让我失望的是每个连字符前面的单词。 如果只是标签,我可以做一些类似(VBP|VBN)+事情,例如,前面的词会有所不同。

His_PRP$ plays_NNS remain_VBP highly_RB popular,_JJ and_CC are_VBP constantly_RB studied._VBN

例如,我将如何编写正则表达式来保留所有NNCC 因此,鉴于如上所示的标记字符串,我如何获得plays_NNS and_CC

我认为您可以使用正则表达式并提取与您的模式匹配的所需子字符串并连接以获得所需的结果字符串。

 String text = "His_PRP$ plays_NNS remain_VBP highly_RB popular,_JJ and_CC are_VBP constantly_RB studied._VBN";
 String pattern = "([^\\s]+_(NNS|CC))";
 String resultText = "";

    // Create a Pattern object
    Pattern r = Pattern.compile(pattern);

    // Now create matcher object.
    Matcher m = r.matcher(text);
    while (m.find( )) 
    {
      resultText = resultText + m.group(0) + " ";
    }

    System.out.println("RESULT: " + resultText);

    /*
    #### OUTPUT #####
    RESULT: plays_NNS and_CC 
    */
[^\s]+_(NNS|CC)

此正则表达式将帮助您仅提取 NNS 和 CC 标签。 您可以在此处使用正则表达式: https : //regex101.com/r/x1VxL0/1

使用过滤方法的非正则表达式解决方案。

public static void main(String []args){

  String inputText = "His_PRP$ plays_NNS remain_VBP highly_RB popular,_JJ and_CC are_VBP constantly_RB studied._VBN";

  String[] tags = {"_NN", "_CC"};
  String[] found = filter(inputText, tags);

  for(int i = 0; i < found.length; i++){
    System.out.println(found[i]);
  }
}

private static String[] filter(String text, String[] tags){

  String[] words = text.split(" "); // Split words by spaces
  ArrayList<String> results = new ArrayList<String>();

  // Save all words that match any of the provided tags
  for(String word : words){
    for(String tag : tags){
      if(word.contains(tag)){
        results.add(word);
        break;
      }
    }
  }
  return results.toArray(new String[0]); // Return results as a string array
}

打印到控制台:

plays_NNS                                                                                                                                                           
and_CC 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM