-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFreq.php
134 lines (124 loc) · 2.85 KB
/
Freq.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
<?php
/**
* @package go\ewp
*/
namespace go\ewp;
/**
* Frequency dictionary compilation
*
* @author Oleg Grigoriev <go.vasac@gmail.com>
*/
class Freq
{
/**
* Constructor
*
* @param string $filename [optional]
*/
public function __construct($filename = null)
{
if ($filename !== null) {
$this->appendFile($filename);
}
}
/**
* Appends a content for parsing
*
* @param string $content
*/
public function appendContent($content)
{
$content = Diacritic::diacritic2latin($content);
if (!\preg_match_all('/[a-z]+/', $content, $matches)) {
return;
}
foreach ($matches[0] as $word) {
if (isset($this->words[$word])) {
$this->words[$word]++;
} else {
$this->words[$word] = 1;
}
}
$this->count += \count($matches[0]);
\arsort($this->words);
}
/**
* Appends a file for parsing of its content
*
* @param string $filename
*/
public function appendFile($filename)
{
$this->appendContent(\file_get_contents($filename));
}
/**
* Get the list of words (sorted by frequency)
*
* @return array
* word => count
*/
public function getWords()
{
return $this->words;
}
/**
* Get the plain list of words
*
* @return array
*/
public function getPlainWordsList()
{
return \array_keys($this->words);
}
/**
* Get the count of all words
*
* @return array
*/
public function getCount()
{
return $this->count;
}
/**
* @param \go\ewp\Parser $parser
* @reutrn array
* (success, fail, uniq, words, puniq, pwords, perunit, perwords)
*/
public function passParser(Parser $parser)
{
$result = (object)[
'success' => [],
'fail' => [],
'uniq' => \count($this->words),
'words' => $this->count,
'pwords' => 0,
'puniq' => 0,
'peruniq' => 0,
'perwords' => 0,
];
if (empty($this->words)) {
return $result;
}
foreach ($this->words as $word => $count) {
$r = $parser->parse($word);
if ($r !== null) {
$result->success[$word] = (string)$r;
$result->puniq++;
$result->pwords += $count;
} else {
$result->fail[] = $word;
}
}
$result->peruniq = (int)($result->puniq * 100 / $result->uniq);
$result->perwords = (int)($result->pwords * 100 / $result->words);
return $result;
}
/**
* @var array
*/
private $words = [];
/**
* @var int
*/
private $count = 0;
}