simhash 0.0.1 → 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,5 @@
1
+ module Simhash
2
+ module Stopwords
3
+ EN = %w{a able about above abst accordance according accordingly across act actually added adj adopted affected affecting affects after afterwards again against ah all almost alone along already also although always am among amongst an and announce another any anybody anyhow anymore anyone anything anyway anyways anywhere apparently approximately are aren arent arise around as aside ask asking at auth available away awfully b back be became because become becomes becoming been before beforehand begin beginning beginnings begins behind being believe below beside besides between beyond biol both brief briefly but by c ca came can cannot can't cause causes certain certainly co com come comes contain containing contains could couldnt d date did didn't different do does doesn't doing done don't down downwards due during e each ed edu effect eg eight eighty either else elsewhere end ending enough especially et et-al etc even ever every everybody everyone everything everywhere ex except f far few ff fifth first five fix followed following follows for former formerly forth found four from further furthermore g gave get gets getting give given gives giving go goes gone got gotten h had happens hardly has hasn't have haven't having he hed hence her here hereafter hereby herein heres hereupon hers herself hes hi hid him himself his hither home how howbeit however hundred i id ie if i'll im immediate immediately importance important in inc indeed index information instead into invention inward is isn't it itd it'll its itself i've j just k keep keeps kept keys kg km know known knows l largely last lately later latter latterly least less lest let lets like liked likely line little 'll look looking looks ltd m made mainly make makes many may maybe me mean means meantime meanwhile merely mg might million miss ml more moreover most mostly mr mrs much mug must my myself n na name namely nay nd near nearly necessarily necessary need needs neither never nevertheless new next nine ninety no nobody non none nonetheless noone nor normally nos not noted nothing now nowhere o obtain obtained obviously of off often oh ok okay old omitted on once one ones only onto or ord other others otherwise ought our ours ourselves out outside over overall owing own p page pages part particular particularly past per perhaps placed please plus poorly possible possibly potentially pp predominantly present previously primarily probably promptly proud provides put q que quickly quite qv r ran rather rd re readily really recent recently ref refs regarding regardless regards related relatively research respectively resulted resulting results right run s said same saw say saying says sec section see seeing seem seemed seeming seems seen self selves sent seven several shall she shed she'll shes should shouldn't show showed shown showns shows significant significantly similar similarly since six slightly so some somebody somehow someone somethan something sometime sometimes somewhat somewhere soon sorry specifically specified specify specifying state states still stop strongly sub substantially successfully such sufficiently suggest sup sure t take taken taking tell tends th than thank thanks thanx that that'll thats that've the their theirs them themselves then thence there thereafter thereby thered therefore therein there'll thereof therere theres thereto thereupon there've these they theyd they'll theyre they've think this those thou though thoughh thousand throug through throughout thru thus til tip to together too took toward towards tried tries truly try trying ts twice two u un under unfortunately unless unlike unlikely until unto up upon ups us use used useful usefully usefulness uses using usually v value various 've very via viz vol vols vs w want wants was wasn't way we wed welcome we'll went were weren't we've what whatever what'll whats when whence whenever where whereafter whereas whereby wherein wheres whereupon wherever whether which while whim whither who whod whoever whole who'll whom whomever whos whose why widely willing wish with within without won't words world would wouldn't www x y yes yet you youd you'll your youre yours yourself yourselves you've z zero}
4
+ end
5
+ end
@@ -0,0 +1,5 @@
1
+ module Simhash
2
+ module Stopwords
3
+ RU = %w{а е и ж м о на не ни об но он мне мои мож она они оно мной много многочисленное многочисленная многочисленные многочисленный мною мой мог могут можно может можхо мор моя моё мочь над нее оба нам нем нами ними мимо немного одной одного менее однажды однако меня нему меньше ней наверху него ниже мало надо один одиннадцать одиннадцатый назад наиболее недавно миллионов недалеко между низко меля нельзя нибудь непрерывно наконец никогда никуда нас наш нет нею неё них мира наша наше наши ничего начала нередко несколько обычно опять около мы ну нх от отовсюду особенно нужно очень отсюда в во вон вниз внизу вокруг вот восемнадцать восемнадцатый восемь восьмой вверх вам вами важное важная важные важный вдали везде ведь вас ваш ваша ваше ваши впрочем весь вдруг вы все второй всем всеми времени время всему всего всегда всех всею всю вся всё всюду г год говорил говорит года году где да ее за из ли же им до по ими под иногда довольно именно долго позже более должно пожалуйста значит иметь больше пока ему имя пор пора потом потому после почему почти посреди ей два две двенадцать двенадцатый двадцать двадцатый двух его дел или без день занят занята занято заняты действительно давно девятнадцать девятнадцатый девять девятый даже алло жизнь далеко близко здесь дальше для лет зато даром первый перед затем зачем лишь десять десятый ею её их бы еще при был про процентов против просто бывает бывь если люди была были было будем будет будете будешь прекрасно буду будь будто будут ещё пятнадцать пятнадцатый друго другое другой другие другая других есть пять быть лучше пятый к ком конечно кому кого когда которой которого которая которые который которых кем каждое каждая каждые каждый кажется как какой какая кто кроме куда кругом с т у я та те уж со то том снова тому совсем того тогда тоже собой тобой собою тобою сначала только уметь тот тою хорошо хотеть хочешь хоть хотя свое свои твой своей своего своих свою твоя твоё раз уже сам там тем чем сама сами теми само рано самом самому самой самого семнадцать семнадцатый самим самими самих саму семь чему раньше сейчас чего сегодня себе тебе сеаой человек разве теперь себя тебя седьмой спасибо слишком так такое такой такие также такая сих тех чаще четвертый через часто шестой шестнадцать шестнадцатый шесть четыре четырнадцать четырнадцатый сколько сказал сказала сказать ту ты три эта эти что это чтоб этом этому этой этого чтобы этот стал туда этим этими рядом тринадцать тринадцатый этих третий тут эту суть чуть тысяч}
4
+ end
5
+ end
@@ -0,0 +1,8 @@
1
+ require File.join(File.dirname(__FILE__), "stopwords", "en")
2
+ require File.join(File.dirname(__FILE__), "stopwords", "ru")
3
+
4
+ module Simhash
5
+ module Stopwords
6
+ ALL = RU + EN
7
+ end
8
+ end
data/lib/simhash.rb CHANGED
@@ -1,56 +1,35 @@
1
- class Simhash
2
- attr_accessor :hashbits, :hash
3
- def initialize(tokens='', hashbits=128)
4
- self.hashbits = hashbits
5
- self.hash = self.simhash(tokens)
6
- hash
7
- end
8
-
9
- def to_s
10
- self.hash.to_s
11
- end
12
-
13
- def to_i
14
- self.hash.to_i
15
- end
16
-
17
- def simhash(tokens)
18
- v = [0] * self.hashbits
1
+ #require 'rubygems'
2
+ #require 'lingua/stemmer'
3
+ $KCODE = 'u'
4
+ require 'active_support/core_ext/string/multibyte'
5
+ require File.join(File.dirname(__FILE__), "simhash", "stopwords")
6
+
7
+ module Simhash
8
+ def self.hash(tokens, options={})
9
+ hashbits = options[:hashbits] || 64
10
+
11
+ v = [0] * hashbits
19
12
  masks = v.dup
20
13
  masks.each_with_index {|e, i| masks[i] = (1 << i)}
14
+
21
15
  tokens.each do |token|
22
- hashed_token = token.hash_wl(self.hashbits)
16
+ token = token.gsub(/(\s|\d|\W)+/u,' ').strip
17
+
18
+ next if token.size < 2
19
+ next if options[:stop_words] && Stopwords::ALL.include?(token.strip.mb_chars.downcase)
20
+
21
+ #token = Lingua.stemmer(token, :language => :ru)
22
+ hashed_token = token.hash_wl(hashbits)
23
23
  bitmask = 0
24
- self.hashbits.times do |i|
24
+ hashbits.times do |i|
25
25
  v[i] += (hashed_token & masks[i]).zero? ? -1 : +1
26
26
  end
27
27
  end
28
28
 
29
29
  fingerprint = 0
30
30
 
31
- self.hashbits.times { |i| fingerprint += 1 << i if v[i] >= 0 }
31
+ hashbits.times { |i| fingerprint += 1 << i if v[i] >= 0 }
32
32
 
33
33
  fingerprint
34
34
  end
35
-
36
- def hamming_distance(other_hash)
37
- self.hash.hamming_distance_to(other_hash.hash)
38
- end
39
-
40
- def string_hash(string)
41
- if string == ""
42
- return 0
43
- else
44
- x = string[0] << 7
45
- m = 1000003
46
- mask = (1<<self.hashbits) - 1
47
- string.each_byte do |char|
48
- x = ((x * m) ^ char) & mask
49
- end
50
-
51
- x ^= string.size
52
- x = -2 if x == -1
53
- x
54
- end
55
- end
56
35
  end
data/lib/string.rb CHANGED
@@ -1,6 +1,6 @@
1
1
  class String
2
- def simhash(hashbits=128)
3
- Simhash.new(self.split, hashbits)
2
+ def simhash(options={})
3
+ Simhash.hash(self.split, options)
4
4
  end
5
5
 
6
6
  # string hash of predefined length
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: simhash
3
3
  version: !ruby/object:Gem::Version
4
- hash: 29
4
+ hash: 25
5
5
  prerelease: false
6
6
  segments:
7
7
  - 0
8
8
  - 0
9
- - 1
10
- version: 0.0.1
9
+ - 3
10
+ version: 0.0.3
11
11
  platform: ruby
12
12
  authors:
13
13
  - Alex Gusev
@@ -15,7 +15,7 @@ autorequire:
15
15
  bindir: bin
16
16
  cert_chain: []
17
17
 
18
- date: 2010-08-11 00:00:00 +04:00
18
+ date: 2010-08-12 00:00:00 +04:00
19
19
  default_executable:
20
20
  dependencies: []
21
21
 
@@ -33,6 +33,9 @@ files:
33
33
  - Rakefile
34
34
  - init.rb
35
35
  - lib/integer.rb
36
+ - lib/simhash/stopwords/en.rb
37
+ - lib/simhash/stopwords/ru.rb
38
+ - lib/simhash/stopwords.rb
36
39
  - lib/simhash.rb
37
40
  - lib/string.rb
38
41
  - rails/init.rb