Home >Backend Development >PHP Tutorial >PHP generates tag cloud based on word frequency

PHP generates tag cloud based on word frequency

WBOY
WBOYOriginal
2016-07-25 08:42:561348browse

Given one piece of text, this code analyzes text's word frequency distribution, generation tag云

  1. /**
  2. * Tag cloud demo based on word frequency
  3. * @author: unknown
  4. * @since: 2007-02-27
  5. */
  6. // Store frequency of words in an array
  7. $freqData = array();
  8. // Random words
  9. $lorem = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec et ipsum gravida
  10. Sed nonummy. For no mass
  11. molestie, but feugiat
  12. Sed soft
  13. pleasant, but no one in risus.
  14. players But what is the land of the land? Mauris no lorem. Aeneas was sad just at the bow. Check and check. For the members Mauritian sauce
  15. diam For convenience. Together with their companions, the mountains will give birth to the feathered and great push, and a ridiculous mouse will be born. Tomorrow and laughter. Proin et dolor laoreet mi
  16. gravida members. You have to drink, you have to put it, you have to put it, you have to run away from the lake, it's a tin can, it's important. Cras eu sem.
  17. ";
  18. // Get individual words and build a frequency table
  19. foreach( str_word_count( $lorem, 1 ) as $word )
  20. {
  21. // For each word found in the frequency table, increment its value by one
  22. array_key_exists( $word, $freqData ) ? $freqData[ $word ]++ : $freqData[ $word ] = 0;
  23. }
  24. // ============= ================================================
  25. / / = Function to actually generate the cloud from provided data =
  26. // =================================== ===========================
  27. function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
  28. {
  29. $minimumCount = min( array_values( $data ) );
  30. $maximumCount = max( array_values( $data ) );
  31. $spread = $maximumCount - $minimumCount;
  32. $cloudHTML = '';
  33. $cloudTags = array() ;
  34. $spread == 0 && $spread = 1;
  35. foreach( $data as $tag => $count )
  36. {
  37. $size = $minFontSize + ( $count - $minimumCount )
  38. * ( $maxFontSize - $minFontSize ) / $spread;
  39. $cloudTags[] = ''
  40. . htmlspecialchars( stripslashes( $tag ) ) . '';
  41. }
  42. return join( "n", $cloudTags ) . "n";
  43. }
  44. ?>
  45. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  46. < ;html xmlns="http://www.w3.org/1999/xhtml">
  47. Tag Cloud Demo
  48. Sample Tag Cloud

  • copy code
  • php, tag
  • Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn