我需要找到所有可以用字符串中的字母组成的英语单词
sentence="Ziegler's Giant Bar"
Run Code Online (Sandbox Code Playgroud)
我可以制作一系列字母
sentence.split(//)
Run Code Online (Sandbox Code Playgroud)
如何从Ruby中的句子中创建超过4500个英语单词?
[编辑]
最好将问题分成几部分:
[假设您可以在一个单词中重复使用源字母]:对于字典列表中的每个单词,构造两个字母数组 - 一个用于候选单词,另一个用于输入字符串.从单词array-of-letters中减去输入的字母数组,如果没有剩下任何字母,你就得到了匹配.执行此操作的代码如下所示:
def findWordsWithReplacement(sentence)
out=[]
splitArray=sentence.downcase.split(//)
`cat /usr/share/dict/words`.each{|word|
if (word.strip!.downcase.split(//) - splitArray).empty?
out.push word
end
}
return out
end
Run Code Online (Sandbox Code Playgroud)
您可以从irb调试器中调用该函数,如下所示:
output=findWordsWithReplacement("some input string"); puts output.join(" ")
Run Code Online (Sandbox Code Playgroud)
...或者这里是一个包装器,您可以使用它从脚本中以交互方式调用该函数:
puts "enter the text."
ARGF.each {|line|
puts "working..."
out=findWordsWithReplacement(line)
puts out.join(" ")
puts "there were #{out.size} words."
}
Run Code Online (Sandbox Code Playgroud)
在Mac上运行时,输出如下所示:
$ ./findwords.rb
输入文字.
Ziegler的巨型酒吧
工作...
a a aa aal aalii Aani Ab aba abaiser abalienate Abantes Abaris abas abase abaser Abasgi abasia Abassin abatable abate abater abatis aba abb abb abbas abbas abbassi abbatial abbess Abbie Abe abear Abel abele Abelia Abelian Abelite abelite abelree Aberia amatia aberrate aberrate abet abettal Abie Abies abietate abiete abietin Abietineae Abiezer Abigail abigail abigeat abilla abcesstate
[....]
Z z za Zabaean zabeta Zabian zabra zabti zabtie zag zain Zan zanella zant zante Zanzalian zanz Zanzibari zar zaratite zareba zat zati zattare Zea zeal zealless zealless zebra zebrass Zebrina zebrine ZEE玉米醇溶蛋白宰斯特ZEL Zelanian Zeltinger禅Zenaga闺房寿热情泽塔ziara济亚拉特黑貂的ZIBET ziega zieger锯齿锯齿zigzagger吉拉诚zingel姜姜百日zinsang Zinzar济拉zirai Zirbanit Zirian Zirianian茭Zizia zizz
有6725个字.
这是超过4500字,但那是因为Mac字词字典非常大.如果你想完全重现Knuth的结果,请从这里下载并解压Knuth的字典:http://www.packetstormsecurity.org/Crackers/wordlists/dictionaries/knuth_words.gz并将"/ usr/share/dict/words"替换为您解压缩替代目录的路径.如果你做对了,你会得到4514个单词,以这个集合结尾:
zanier zanies zanzan zanzibar zazen zeal zebra zebras Zeiss zeitgeist Zen Zennist zest zestier zeta Ziegler zig zigging zigzag zigzagging zigzags zing zingier zings zinnia
我相信这回答了原来的问题.
或者,提问者/读者可能想要列出可以从字符串构造的所有单词而不重用任何输入字母.我建议的代码完成如下工作:复制候选词,然后对输入字符串中的每个字母,从副本中破坏性地删除该字母的第一个实例(使用"slice!").如果此过程吸收了所有字母,请接受该字词.
def findWordsNoReplacement(sentence)
out=[]
splitInput=sentence.downcase.split(//)
`cat /usr/share/dict/words`.each{|word|
copy=word.strip!.downcase
splitInput.each {|o| copy.slice!(o) }
out.push word if copy==""
}
return out
end
Run Code Online (Sandbox Code Playgroud)