【问题标题】:Dart: Is there a way to split strings into sentences without using Dart's split method?Dart:有没有不使用 Dart 的 split 方法将字符串拆分成句子的方法?
【发布时间】:2020-06-25 15:46:17
【问题描述】:

我希望使用 Dart 将一段文本拆分成单独的句子。我遇到的问题是句子可以以许多标点符号结尾(例如“。”,“!”,“?”),在某些情况下(例如日语),句子可以以独特的符号结尾(例如'。')。

此外,Dart 的 split 方法会从字符串中删除拆分值。例如,“Hello World!”在使用代码text.split('! ');时变为“Hello World”

我查看了可用的 Dart 包,但找不到任何符合我要求的东西。

理想情况下,我正在寻找类似于 Java 中的 BreakIterator 的东西,它允许程序员在检测标点符号时定义他们希望使用的语言环境,并在将字符串拆分为句子时维护标点符号。我很高兴在 Dart 中使用一种不会根据 Locale 自动检测句子结尾的解决方案,但如果这不可用,我希望能够定义所有句子结尾以在拆分字符串时查找。

感谢任何帮助。提前谢谢你。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    可以使用正则表达式完成,如下所示:

      String str1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In vulputate odio eros, sit amet ultrices ipsum auctor sed. Mauris in faucibus elit. Nulla quam orci? ultrices a leo a, feugiat pharetra ex. Nunc et ipsum lorem. Integer quis congue nisi! In et sem eget leo ullamcorper consectetur dignissim vitae massa。Nam quis erat ac tellus laoreet posuere. Vivamus eget sapien eget neque euismod mollis.";
    
      // regular expression:
      RegExp re = new RegExp(r"(\w|\s|,|')+[。.?!]*\s*");
    
      // get all the matches:
      Iterable matches = re.allMatches(str1);
    
      //  Iterate all matches:
      for (Match m in matches) {
        String match = m.group(0);
        print("match: $match");
      }
    

    输出:

    // match: Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
    // match: In vulputate odio eros, sit amet ultrices ipsum auctor sed. 
    // match: Mauris in faucibus elit. 
    // match: Nulla quam orci? 
    // match: ultrices a leo a, feugiat pharetra ex. 
    // match: Nunc et ipsum lorem. 
    // match: Integer quis congue nisi! 
    // match: In et sem eget leo ullamcorper consectetur dignissim vitae massa。
    // match: Nam quis erat ac tellus laoreet posuere. 
    // match: Vivamus eget sapien eget neque euismod mollis.
    

    【讨论】:

    • 这非常有效。太感谢了!一个简单的问题,当向列表添加匹配项时,为什么列表末尾有一个额外的空输入(即[sentence 1., Sentence 2!, Sentence 3?, ];)?
    • 更新了答案,现在试试,你是对的,我从第一部分中删除了不需要的 *(匹配 0 个或多个:空格、单词、允许的特殊字符),现在只有 + 号 (至少匹配一个或多个)。如果您觉得答案有帮助,请标记为已接受,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    相关资源
    最近更新 更多