Partager via


F# and Wordle

For those of us, who have not yet heard of Wordle:

Wordle is a toy for generating “word clouds” from text that you provide. The clouds give greater prominence to words that appear more frequently in the source text. You can tweak your clouds with different fonts, layouts, and color schemes. The images you create with Wordle are yours to use however you like. You can print them out, or save them to the Wordle gallery to share with your friends.

But since (often) a picture says  more than … See the following (small) image of what Wordle might do for you:

Now, Wordle may generate word clouds by poiting it to your word source or by posting a collection of "(frequency-weighted) words to the wordle site. Consequently, this is what the following snippet is all about. It is based on the MSDN article “How to: Send Data Using the WebRequest Class”. I followed the imperative blue print and did not use F# heavyweights like async.

 

  1: open System.Net
  2:  
  3: let words = ""
  4:  
  5: let worddleUrl = "https://www.wordle.net/advanced"
  6:  
  7: let r = System.Net.WebRequest.Create(worddleUrl)
  8: r.Credentials <- CredentialCache.DefaultCredentials
  9: r.Method <- "POST"
  10: r.ContentType <- "application/x-www-form-urlencoded"
  11: let s = r.GetRequestStream()
  12: let wordsEncoded = System.Text.Encoding.UTF8.GetBytes ("text="+ words);
  13: let wordsLen = ( Array.length wordsEncoded )
  14: s.Write(wordsEncoded, 0, wordsLen)
  15: s.Close()
  16:  
  17: let response = r.GetResponse()
  18: let responseStream = response.GetResponseStream()
  19: using ( new System.IO.StreamReader(responseStream)) (fun sr ->
  20:   let responseText = sr.ReadToEnd()
  21:   using (System.IO.File.CreateText("/response.htm")) (fun wr ->
  22:     wr.Write(responseText)
  23:   )
  24: )

 

The code is quite simple, supply space-delimited words in the words variable (e.g., "hello world”) or you might even use frequency-weighted words using the syntax “word:frequency” where frequency is a natural number like 3. The rest of the code follows the mentioned MSDN sample, i.e. using a WebRequest to contact the Wordle service, waiting for a response and writing the response to a local html file. Now, you might have expected that the result from a Wordle call is an image representation of a word cloud. This is not the case, instead what you get is an HTML with the Wordle Java applet, which when started will actually render your word cloud. Now, what you get is a “suggestion” or one version to render your words as a word cloud. However, the applet provides some level of customisability, i.e. changing word-placement strategy, color, font, etc. Lastly, you might want to print your word cloud, for example, as a pdf. Unfortunately, you cannot export the word cloud into an image container but you may use a screen-shotting device to achieve a similar result.

With that happy word clouding with the excellent Wordle.