2010-12-31 16 views
6

Sto ricevendo i miei ultimi tweet con HTTParty e Hashie in questo modo.Trasforma gli URL e @ * nei link

tweet = Hashie::Mash.new HTTParty.get(http://twitter.com/statuses/user_timeline/ethnt.json).first 
puts tweet.text 

Voglio essere in grado di trasformare ogni link (http://*.*) e nomi utente (@.) in link. Quale sarebbe la regex per entrambi, e come la implementerei?

+0

Questa non è una soluzione, ma assicurati di guardare le entità Tweet nel documento - Twitter farà tutto questo lavoro per te in anticipo. http://developer.twitter.com/pages/tweet_entities –

risposta

4
def link_urls_and_users s 

    #regexps 
    url = /(|^)http:\/\/([^\s]*\.[^\s]*)(|$)/ 
    user = /@(\w+)/ 

    #replace @usernames with links to that user 
    while s =~ user 
     s.sub! "@#{$1}", "<a href='http://twitter.com/#{$1}' >#{$1}</a>" 
    end 

    #replace urls with links 
    while s =~ url 
     name = $2 
     s.sub! /(|^)http:\/\/#{name}(|$)/, " <a href='http://#{name}' >#{name}</a> " 
    end 

    s 

end 


puts link_urls_and_users(tweet.text) 

Questo funziona, a patto che gli URL vengono riempiti da spazi o sono all'inizio e/o alla fine del tweet.

+0

Funziona perfettamente, grazie. –

+0

Se il post contiene un punto interrogativo, questo codice mi scorre infinito per me in ruby ​​1.87. Prova ad alimentare: s = "Snif http://www.youtube.com/watch?v=V7676EC06oc&feature=related" – Joelio

+0

Potrebbe non essere l'opzione migliore, ma ho aggiunto/modificato la sezione s = ~ a: match_name = name.gsub ("?", "\\?") match_name = match_name.gsub ("&", "\\ &") s.sub!/(| ^) http: \/\/# {match_name} (| $) /, "#{name}" – Joelio

0

si può provare questo:

# Arrays 
links = []  
usernames = [] 

links = tweet.text.scan(/(http:\/\/\w+(\.?\w+(:\d+)?\/?)+)/i).map{|e| e[0]} 
usernames = tweet.text.scan(/@(\w+)/i).map{|e| "<a href='http://twitter.com/#{e[0]}'>@#{e[0]}</a>"} 

L'espressione regolare per l'URL non è perfetto, ma abbastanza buono per quelli comuni.

1

Questo progetto è un metodo per esso: https://github.com/mzsanford/twitter-text-rb

Dalle loro documentazione:

class MyClass 
    include Twitter::Extractor 
    usernames = extract_mentioned_screen_names("Mentioning @twitter and @jack") 
    # usernames = ["twitter", "jack"] 
end 
2

Per trovare gli URL nel testo, perché non riutilizzare una ruota esistente invece di inventare una nuova?

require 'uri' 
require 'open-uri' 

body = open('http://stackoverflow.com/questions/4571229/turn-urls-and-into-links').read 
uris = URI::extract(body) 
uris.size # => 102 
uris.first # => "http://www.w3.org/TR/html4/strict.dtd" 
uris.last # => "http://edge.quantserve.com/quant.js" 

Aggiungere alla risposta data da @stef e il gioco è fatto.

0

Espansione della risposta di Tin Man, c'è una semplice fodera per rendere cliccabili gli URL.

URI::extract(body).each { |uri| body.gsub!(uri, %Q{<a href="#{uri}">#{uri}</a>})} 

Avrete quindi bisogno di utilizzare body.html_safe se in Rails. Per gli utenti di Twitter, dovresti davvero fare affidamento sull'API di Twitter per dirti cosa è e non è un nome utente valido, perché possono filtrare correttamente "@looksvalid" quando non c'è un utente con quel nome.