Skip to content

Instantly share code, notes, and snippets.

@mathfur
Created March 14, 2010 13:40
Show Gist options
  • Save mathfur/331976 to your computer and use it in GitHub Desktop.
Save mathfur/331976 to your computer and use it in GitHub Desktop.
# [単語\t絶対パス\t行番号]のファイルから単語検索する
require "digest/md5"
wanna_search = ARGV[1]
ext = ARGV[0]
context = (ARGV[2] || 1).to_i
max_output = (ARGV[3] || 10).to_i
unless wanna_search && ext
STDERR.puts "args error"
end
$verbose = false
def get_key_path_num(str)
if str =~ /^([0-9a-f]+)\t([^\t]*)\t([0-9]+)$/
target_key = $1.to_i(16)
target_path = $2
target_num = $3.to_i
#STDERR.puts "#{target_key},#{target_path},#{target_num}"
end
return target_key, target_path, target_num
end
# range: 整数, 前後どのくらいの行数を表示するか
def search_by_key(key,lines)
raise "search_by_key: keyは整数で指定する" unless key.kind_of?(Integer)
STDERR.puts "search_by_key(#{key},#{lines.size})" if $verbose
half_point = (lines.size/2).floor
#STDERR.puts "lines[half_point]:#{lines[half_point]}"
if lines[half_point] =~ /^([0-9a-f]+)\t([^\t]*)\t([0-9]+)$/
target_key = $1.to_i(16)
target_path = $2
target_num = $3.to_i
#STDERR.puts "#{target_key},#{target_path},#{target_num}"
end
STDERR.puts "target_key:#{target_key} <-> key:#{key}" if $verbose
STDERR.puts "half_point: #{half_point}" if $verbose
if target_key == key
STDERR.puts "==" if $verbose
surround_results = [lines[half_point]]
i=0
# 前に同じ結果が並んでいればそれも得る
while (lines[half_point-i]||"") =~ /^[0-9a-f]+/ && $~[0].to_i(16)==key
surround_results << lines[half_point-i]
i+=1
end
i=0
# 後ろに同じ結果が並んでいればそれも得る
while (lines[half_point+i]||"") =~ /^[0-9a-f]+/ && $~[0].to_i(16)==key
surround_results << lines[half_point+i]
i+=1
end
#return surround_results.map{|ln| ln=~/^([0-9a-f]+)\t([^\t]*)\t([0-9]+)$/ && [$2,$3] }.compact
return surround_results
elsif target_key < key && half_point < lines.size-1
STDERR.puts "<" if $verbose
return search_by_key(key,lines[half_point+1..-1])
elsif target_key > key && half_point > 0
STDERR.puts ">" if $verbose
return search_by_key(key,lines[0..half_point-1])
else
return nil
end
end
path = "C:/sample_codes"
results = search_by_key(Digest::MD5.hexdigest(wanna_search).to_i(16),File.read("#{path}/indexed_of_#{ext}.txt").split("\n").map{|s| s.strip})
results[0..max_output].compact.map{|e| e.split("\t")}.each do |key,path,num|
puts "="*30
((num.to_i - context)..(num.to_i+context)).to_a.each do |i|
puts File.read(path).split("\n")[i]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment