Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- ### 文字列とIDから、転置インデックスを生成する
- # str: 対象文字列
- # id: 文書ID
- # opt:
- # n: N-gramのN
- # index: 生成済みindex
- def indexize(str, id, opt={})
- n = opt[:n] || 2
- index = opt[:index] || {}
- chars = str.strip.split(//)
- tokens = tokenize(chars, n)
- tokens.each.with_index do |token, i|
- index[token] ||= []
- index[token] << "#{id}:#{i}"
- end
- return index
- end
- ### 文字配列から、N-gram用のトークン配列を生成する
- def tokenize(chars, n)
- (0 .. chars.size - n).map do |i|
- grams = (0 .. n-1).map{|j| chars[i+j].chomp }
- next if grams.any?(&:empty?)
- grams.join
- end
- end
- id = 1 # XXX: IDは外部から渡したい
- indexize(STDIN.read, id).each do |k, v|
- puts "#{k}\t#{v.join(",")}"
- end
Add Comment
Please, Sign In to add comment