为了账号安全,请及时绑定邮箱和手机立即绑定

如何拆分多个连接词?

如何拆分多个连接词?

守着一只汪 2019-10-05 15:26:22
我有大约1000个条目的数组,下面是示例:wickedweatherliquidweatherdriveourtrucksgocompactslimprojector我希望能够将它们分为各自的词,例如:wicked weatherliquid weatherdrive our trucksgo compactslim projector我希望我能做到一个正则表达式。但是,由于我没有止境可言,因此我也没有可能要大写的任何大写字母,因此可能需要某种对字典的引用?我想可以手工完成,但是为什么-什么时候可以用代码完成!=)但是,这让我感到难过。有任何想法吗?
查看完整描述

3 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

最好的工具是递归,而不是正则表达式。基本思想是从字符串的开头开始寻找一个单词,然后从字符串的其余部分开始寻找另一个单词,依此类推,直到到达字符串的末尾。递归解决方案是很自然的,因为当字符串的给定其余部分不能分解为一组单词时,需要进行回溯。下面的解决方案使用词典来确定什么是单词,并在找到它们时打印出解决方案(一些字符串可以分解为多个可能的单词组,例如wickedweather可以解析为“对我们不利”)。如果您只想要一组单词,则需要确定选择最佳单词的规则,


#!/usr/bin/perl


use strict;


my $WORD_FILE = '/usr/share/dict/words'; #Change as needed

my %words; # Hash of words in dictionary


# Open dictionary, load words into hash

open(WORDS, $WORD_FILE) or die "Failed to open dictionary: $!\n";

while (<WORDS>) {

  chomp;

  $words{lc($_)} = 1;

}

close(WORDS);


# Read one line at a time from stdin, break into words

while (<>) {

  chomp;

  my @words;

  find_words(lc($_));

}


sub find_words {

  # Print every way $string can be parsed into whole words

  my $string = shift;

  my @words = @_;

  my $length = length $string;


  foreach my $i ( 1 .. $length ) {

    my $word = substr $string, 0, $i;

    my $remainder = substr $string, $i, $length - $i;

    # Some dictionaries contain each letter as a word

    next if ($i == 1 && ($word ne "a" && $word ne "i"));


    if (defined($words{$word})) {

      push @words, $word;

      if ($remainder eq "") {

        print join(' ', @words), "\n";

        return;

      } else {

        find_words($remainder, @words);

      }

      pop @words;

    }

  }


  return;

}


查看完整回答
反对 回复 2019-10-05
  • 3 回答
  • 0 关注
  • 595 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信