2009-07-27 16 views
12

Esiste un modo migliore per formattare il testo da Twitter per collegare i collegamenti ipertestuali, il nome utente e gli hashtag? Quello che ho sta funzionando, ma so che questo potrebbe essere fatto meglio. Sono interessato a tecniche alternative. Lo sto configurando come HTML Helper per ASP.NET MVC.Formattazione del testo Twitter (TweetText) con C#

using System; 
using System.Collections.Generic; 
using System.Text.RegularExpressions; 
using System.Web; 
using System.Web.Mvc; 

namespace Acme.Mvc.Extensions 
{ 

    public static class MvcExtensions 
    { 
     const string ScreenNamePattern = @"@([A-Za-z0-9\-_&;]+)"; 
     const string HashTagPattern = @"#([A-Za-z0-9\-_&;]+)"; 
     const string HyperLinkPattern = @"(http://\S+)\s?"; 

     public static string TweetText(this HtmlHelper helper, string text) 
     { 
      return FormatTweetText(text); 
     } 

     public static string FormatTweetText(string text) 
     { 
      string result = text; 

      if (result.Contains("http://")) 
      { 
       var links = new List<string>(); 
       foreach (Match match in Regex.Matches(result, HyperLinkPattern)) 
       { 
        var url = match.Groups[1].Value; 
        if (!links.Contains(url)) 
        { 
         links.Add(url); 
         result = result.Replace(url, String.Format("<a href=\"{0}\">{0}</a>", url)); 
        } 
       } 
      } 

      if (result.Contains("@")) 
      { 
       var names = new List<string>(); 
       foreach (Match match in Regex.Matches(result, ScreenNamePattern)) 
       { 
        var screenName = match.Groups[1].Value; 
        if (!names.Contains(screenName)) 
        { 
         names.Add(screenName); 
         result = result.Replace("@" + screenName, 
          String.Format("<a href=\"http://twitter.com/{0}\">@{0}</a>", screenName)); 
        } 
       } 
      } 

      if (result.Contains("#")) 
      { 
       var names = new List<string>(); 
       foreach (Match match in Regex.Matches(result, HashTagPattern)) 
       { 
        var hashTag = match.Groups[1].Value; 
        if (!names.Contains(hashTag)) 
        { 
         names.Add(hashTag); 
         result = result.Replace("#" + hashTag, 
          String.Format("<a href=\"http://twitter.com/search?q={0}\">#{1}</a>", 
          HttpUtility.UrlEncode("#" + hashTag), hashTag)); 
        } 
       } 
      } 

      return result; 
     } 

    } 

} 
+0

stringa const HyperLinkPattern = @ "(http (s)?: // \ S +) \ s?"; // Supporto https anche – NetProvoke

risposta

3

Questo è notevolmente simile al codice che ho scritto che visualizza il mio stato di Twitter sul mio blog. Le uniche cose che faccio sono:

1) cercare @name e sostituirlo con <a href="http://twitter.com/name">Real Name</a>;

2) più @name in una riga ricevono le virgole, se non ce l'hanno;

3) I tweet che iniziano con @name(s) sono formattati "To @name:".

Non vedo alcun motivo per cui questo non può essere un modo efficace per analizzare un tweet - sono un formato molto coerente (buono per espressioni regolari) e nella maggior parte delle situazioni la velocità (millisecondi) è più che accettabile.

Edit:

Here is the code for my Tweet parser. E 'un po' troppo lungo per mettere in una risposta Stack Overflow. Ci vuole un tweet come:

@ user1 @ user2 controlla questo link fresco che ho ricevuto da @ user3: http://url.com/page.htm#anchor #coollinks

e lo trasforma in:

<span class="salutation"> 
    To <a href="http://twitter.com/user1">Real Name</a>, 
    <a href="http://twitter.com/user2">Real Name</a>: 
</span> check out this cool link I got from 
<span class="salutation"> 
    <a href="http://www.twitter.com/user3">Real Name</a> 
</span>: 
<a href="http://site.com/page.htm#anchor">http://site.com/...</a> 
<a href="http://twitter.com/#search?q=%23coollinks">#coollinks</a> 

Inoltre racchiude tutto quel markup in un piccolo JavaScript:

document.getElementById('twitter').innerHTML = '{markup}'; 

Questo è così il tweet fetcher può essere eseguito in modo asincrono come JS e se Twitter è inattivo o lento non influirà sul tempo di caricamento della pagina del mio sito.

+0

Ho un problema con il mio codice se un URL ha un carattere hash. Ho provato a usare \ b per definire i confini delle parole ma non funziona. Non sono sicuro che l'esempio di Django funzionerà per me in C# ma lo sto provando. – Brennan

+0

@Brennan per quanto posso dire, hashtag può essere alfanumerico. Catturare gli URL prima (in questo modo si cattura qualsiasi URL con #), quindi eseguire l'espressione regolare hashtag sui frammenti che non sono stati rilevati dal sostituto URL. –

+0

Non sono sicuro di come farlo con Regex in C#. Hai un esempio? – Brennan

0

Ho creato il metodo di supporto per abbreviare il testo a 140 caratteri con URL incluso. Puoi impostare la lunghezza della condivisione su 0 per escludere l'url dal tweet.

public static string FormatTwitterText(this string text, string shareurl) 
    { 
     if (string.IsNullOrEmpty(text)) 
      return string.Empty; 

     string finaltext = string.Empty; 
     string sharepath = string.Format("http://url.com/{0}", shareurl); 

     //list of all words, trimmed and new space removed 
     List<string> textlist = text.Split(' ').Select(txt => Regex.Replace(txt, @"\n", "").Trim()) 
           .Where(formatedtxt => !string.IsNullOrEmpty(formatedtxt)) 
           .ToList(); 

     int extraChars = 3; //to account for the two dots ".." 
     int finalLength = 140 - sharepath.Length - extraChars; 
     int runningLengthCount = 0; 
     int collectionCount = textlist.Count; 
     int count = 0; 
     foreach (string eachwordformated in textlist 
       .Select(eachword => string.Format("{0} ", eachword))) 
     { 
      count++; 
      int textlength = eachwordformated.Length; 
      runningLengthCount += textlength; 
      int nextcount = count + 1; 

      var nextTextlength = nextcount < collectionCount ? 
              textlist[nextcount].Length : 
              0; 

      if (runningLengthCount + nextTextlength < finalLength) 
       finaltext += eachwordformated; 
     } 

     return runningLengthCount > finalLength ? finaltext.Trim() + ".." : finaltext.Trim(); 
    } 
0

C'è una buona risorsa per l'analisi dei messaggi di Twitter questo link, ha lavorato per me:

Come analizzare Twitter nomi utente, hashtag e gli URL in C# 3,0

http://jes.al/2009/05/how-to-parse-twitter-usernames-hashtags-and-urls-in-c-30/

Contiene il supporto per:

  • Urls
  • #hashtags
  • @nomi utente

BTW: Regex nel parseURL() metodo ha bisogno revisione, analizza simboli di borsa (BARC.L) in link.

Problemi correlati