Add popularity script
[milivella] / vella_xref.rb
1 #!/usr/bin/env ruby
2
3 require 'net/http'
4 require 'uri'
5
6 GOOGLE_SEARCH_URL = "http://www.google.com/xhtml/search?hl=en&q=%s"
7
8 def google_hits(*stuff)
9         keys = stuff.map { |w|
10                 "\"#{w}\""
11         }
12         url = GOOGLE_SEARCH_URL % URI::escape(keys.join(" "))
13         xml = Net::HTTP::get(URI.parse(url))
14         have = xml.match(/Results .*? of about (.*?)\. <br\/>/)
15         if have
16                 return have[1].gsub(',','').to_i
17         else
18                 return 0
19         end
20 end
21
22 risultati = Hash.new
23
24 singole = Array.new
25
26 while gets
27         next unless w = chomp.intern rescue nil
28         next if singole.include?(w)
29         singole << w
30         risultati[w] = google_hits(w) unless risultati.has_key?(w)
31         # puts "%s => %d" % [w, risultati[w]]
32 end
33
34 puts "Fine ricerca parole"
35
36 # TODO nel costruire l'Array di coppie
37 # assumiamo che per Google sia la stessa cosa cercare
38 # A B e B A, cosa che potrebbe non essere vera ...
39
40 coppie = Array.new
41
42 copia = singole.dup
43 while w = copia.shift
44         copia.each { |ww|
45                 coppie << [w, ww]
46         }
47 end
48
49 coppie.each { |ar|
50         risultati[ar] = google_hits(*ar) unless risultati.has_key?(ar)
51         # puts "(%s, %s) => #{risultati[ar]}" % ar
52 }
53
54 puts "Fine ricerca coppie"
55
56 risultati.each { |chiave, valore|
57         # Salta questa chiave se non è un vettore
58         next unless chiave.kind_of? Array
59         # _chiave_ è una coppia, [x, y], _valore_ è pxy
60         # Vogliamo sputare fuori x, y, px, py, pxy.
61         # Costruiamo un nuovo vettore i cui primi due
62         # elementi sono [x, y]
63         out = chiave.dup
64         # Aggiungiamo px e py, ovvero risultati[_]
65         # per ciascun elemento di _chiave_
66         chiave.each { |w|
67                 out << risultati[w]
68         }
69         # ed infine pxy:
70         out << valore
71         # Ora out è [x, y, px, py, pxy]; lo vogliamo sputare fuori
72         # separando gli elementi con una virgola:
73         puts out.join(", ")
74 }