3 回答
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;
}
- 3 回答
- 0 关注
- 622 浏览
添加回答
举报