Pull to refresh

Считаем слова в текстах

Reading time3 min
Views3.6K
Привет, хабр! Буквально недавно я узнал о том, что в произведениях русской литературы буква «о» пользуется большей популярностью, чем остальные и мгновенно вспомнил о своей давней идее написать простенький скрипт, который будет из указанного текста составлять список самых используемых слов.

Иногда возникает необходимость читать тексты на английском языке, но поскольку мой словарный запас не настолько богат, чтобы все понимать на лету, приходится часто отвлекаться на использование словаря. Многие слова встречаются очень часто, но не всегда получается после первого ознакомления с переводом слова вбить его себе в голову. И здесь приходит на помощь этот чудо-топ. Все безумно просто: на входе исходный текст, на выходе список N самых используемых слов, которые в дальнейшем забиваем в переводчик и получаем словарик к нашему тексту.

Так как в моей голове оставил след только PHP, было решено писать на нем, ибо требование к скрипту только одно — результат.
  1. #!/usr/bin/php
  2. <?php
  3.  
  4. if (!isset($argv[1])) {
  5.     die('Usage: ./wtop filename [lines] [filter]' . PHP_EOL .
  6.     'Use -1 lines for show all words' . PHP_EOL);
  7. }
  8. if (!file_exists($argv[1]) || !is_readable($argv[1])) {
  9.     die('Data file not found or can not be read . PHP_EOL');
  10. }
  11. if (isset($argv[3])) {
  12.     if (file_exists($argv[3]) && is_readable($argv[3])) {
  13.         $filter = str_word_count(file_get_contents($argv[3]), 1);
  14.     } else {
  15.         die('Filter file not found or can not be read' . PHP_EOL);
  16.     }
  17. }
  18.  
  19. $lines = (isset($argv[2])) ? (int) $argv[2] : -1;
  20.  
  21. $data = file_get_contents($argv[1]);
  22. $words = str_word_count($data, 1);
  23.  
  24. foreach ($words as $word) {
  25.     $word = strtolower($word);
  26.     if (isset($filter) && in_array($word, $filter)) {
  27.         continue;
  28.     }
  29.     if (isset($result[$word])) {
  30.         $result[$word] += 1;
  31.     } else {
  32.         $result[$word] = 1;
  33.     }
  34. }
  35.  
  36. arsort(&$result);
  37.  
  38. foreach ($result as $word => $count) {
  39.     if ($lines-- == 0) {
  40.         break;
  41.     }
  42.     echo $count . ' ' . $word . PHP_EOL;
  43. }

Пример работы:
stream@sapphire:~/development$ cat text.txt
With PHP breaking new ground in the enterprise arena, the establishment of a rati-
fied certification was, some might say, inevitable. However, for me, it couldn’t come
soon enough—and I was ecstatic when Zend launched their PHP 4 Certification.
With more than 1,500 certified engineers to date, there is no doubt that their en-
deavour has been a success.
Now, with the introduction of the long-awaited PHP 5 certification, Zend has once
again raised the bar for PHP developers everywhere. This examination is much
broader, and requires much more than just theoretical knowledge—in order to pass
the test, candidates need real-world knowledge in addition to a solid theoretical
background.
The effect of the PHP 5 certification, for me, is even more profound than that of
the original certification, and I believe that it will become the gold standard for those
looking to hire PHP-centric Web Developers. I think that it is apt to consider Zend’s
work a job well done, and to applaud those who invest the time and effort needed to
become Zend Certified Engineers.
stream@sapphire:~/development$ cat filter.txt
a the
am are
i you we
stream@sapphire:~/development$ ./wtop text.txt 10 filter.txt
7 to
5 and
5 certification
5 php
4 for
4 is
4 that
4 of
4 zend
3 more
stream@sapphire:~/development$


Надеюсь, кому-нибудь будет полезно. Удачи!

Update: переписал небольшой кусок кода (thank DevMan), добавил поддержку фильтра.
Tags:
Hubs:
Total votes 30: ↑14 and ↓16-2
Comments19

Articles