2009-03-31 9 views

答えて

2

最も簡単な方法は「にファイルとgrepからのデータのチャンクを読み込む」よりはありませんが、決して最速、単に単語に対して検索することです毎回リストする。単語リストが配列である場合:

if word_list.index word 
    #manipulate word 
end 

場合は、しかし、あなたは、その後、我々はそれを見つけるためにFile#foreachを使用します(個別の行に各単語と)別のファイルとして単語リストを持っていた:

if File.foreach("word.list") {|x| break x if x.chomp == word} 
    #manipulate word 
end 

foreachは末尾に改行文字(複数可)をはがしていないので、私たちはString#chompでそれらを取り除くことに注意してください。

+0

これはトリックでした...単語が一致しない場合、私はプログラムをラップしてエラーメッセージを作成することができました。ありがとう。 – supergalactic

0

あなたはファイルからリストを読んでいますか? あなたはそれをすべてメモリに保存できませんか?ない場合 は多分finger treeはあなたに を助けるかもしれない、そこ

2

ここでは、Setを使用した簡単な例ですが、マーク・ジョンソン氏は正しいですが、 ブルームフィルタがより効率的になります。

require 'set' 

WORD_RE = /\w+/ 

# Read in the default dictionary (from /usr/share/dict/words), 
# and put all the words into a set 
WORDS = Set.new(File.read('/usr/share/dict/words').scan(WORD_RE)) 

# read the input line by line 
STDIN.each_line do |line| 
    # find all the words in the line that aren't contained in our dictionary 
    unrecognized = line.scan(WORD_RE).find_all { |term| not WORDS.include? term } 

    # if none were found, the line is valid 
    if unrecognized.empty? 
    puts "line is valid" 
    else # otherwise, the line contains some words not in our dictionary 
    puts "line is invalid, could not recognize #{unrecognized.inspect}" 
    end 
end 
+0

あなたは明らかに私よりもはるかに多くの経験を持っています:)私はこれを勉強します – supergalactic

+0

私は少し上手な学習ガイドにするために私の例をマークアップします。 – rampion

0

メモリに単語リストを読み、各単語について、ハッシュテーブルへのエントリを入力します。

def init_word_tester 
    @words = {} 

    File.foreach("word.list") {|word| 
     @words[word.chomp] = 1 
    } 
end 

今あなたは自分のハッシュに対するすべての単語を確認することができます。

def test_word word 
    return @words[word] 
end