blib/lib/CEDict/Pinyin.pm

filter: Statementstmt 57.0% 65 / 114 Branchbran 39.6% 23 / 58 Conditioncond 14.2% 2 / 14 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 71.4% 10 / 14 Podpod 80.0% 4 / 5 totaltotal 49.0% 104 / 212 CC 37 SCAR 41.4
CC
37
Cov
48%
buildRegex
156.0
diacritic
110.0
_isValidInitialSubstring
12.0
CRAP 62.8
↑ Summary
1 package CEDict::Pinyin;
2 # Copyright (c) 2009 Christopher Davaz. All rights reserved.
3 # This program is free software; you can redistribute it and/or
4 # modify it under the same terms as Perl itself.
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use base qw(Class::Light);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 1 $VERSION = '0.02004';
13  
14 =encoding utf8
15  
16 =head1 NAME
17  
18 CEDict::Pinyin - Validates pinyin strings
19  
20 =head1 SYNOPSIS
21  
22 # This is from the test case provided with this module:
23  
24 use CEDict::Pinyin;
25  
26 my @good = ("ji2 - rui4 cheng2", "xi'an", "dian4 nao3, yuyan2", "kongzi");
27 my @bad = ("123", "not pinyin", "gu1 gu1 fsck4 fu3");
28 my $py = CEDict::Pinyin->new;
29  
30 for (@good) {
31 $py->setSource($_);
32 ok($py->isPinyin, "correctly validated good pinyin");
33 print "pinyin: " . $py->getSource . "\n";
34 print "parts: " . join(', ', @{$py->getParts}) . "\n";
35 }
36  
37 for (@bad) {
38 $py->setSource($_);
39 ok(!$py->isPinyin, "correctly invalidated bad pinyin");
40 print "pinyin: " . $py->getSource . "\n";
41 print "parts: " . join(', ', @{$py->getParts}) . "\n";
42 }
43  
44 =head1 DESCRIPTION
45  
46 This class helps you validate and parse pinyin. Currently the pinyin must follow
47 some rules about how it is formatted before being considered "valid" by this
48 class's validation method. All valid pinyin syllables are expressed by characters
49 within the 7-bit ASCII range. That means the validation method will fail on a
50 string like "nán nǚ lǎo shào". The pinyin should instead contain numbers after
51 the letter to represent tones. Instead of the string above we should use
52 "nan2 nv lao3 shao4". Being able to accept a string with accented characters
53 that represent the tone of the syllable is a feature I hope to add to a future
54 version of this module. The parser first takes a look at the entires string
55 you pass it to see if it is even worth parsing. The regular expression used
56 is shown below.
57  
58 C<< /^[A-Za-z]+[A-Za-z1-5,'\- ]*$/ >>
59  
60 If the pinyin doesn't match this regex, then isPinyin returns false and stops
61 parsing the string. All this means is that if you want to use this module to
62 validate your pinyin but your pinyin is not exactly in the same format as
63 just described then you need cleanup your pinyin strings a little bit first.
64  
65 Again, hopefully future versions of this class will be more flexible in what
66 is accepted as valid pinyin. However we want to be sure that what we are looking
67 at is really pinyin and not some English words as this module was originally
68 written in part to distinguish between a pinyin string and English. I would
69 also like to keep this idea in future versions, so if you update the class
70 with your own code, please keep that in mind.
71  
72 =cut
73  
74 # Class Data defined here
75 1 my %ValidPinyin;
76 1 ▶$ValidPinyin{$_} = chomp $_ while <DATA>;
Branch: 1 branch
BranchTrueFalseTotal
defined($_ = readline DATA) and do { $ValidPinyin{$_} = chomp $_ } 407 1 408
77 1 close DATA;
78  
79 # Characters containing the diacritic marks used in pinyin. The array is ordered
80 # by tone number (however since arrays are 0-indexed the first-tone diacritic
81 # information is at $Tones[0]).
82 1 my @Tones = (
83 {a=>"\x{0101}",e=>"\x{0113}",i=>"\x{012B}",o=>"\x{014D}",u=>"\x{016B}",v=>"\x{01D6}"},
84 {a=>"\x{00E1}",e=>"\x{00E9}",i=>"\x{00ED}",o=>"\x{00F3}",u=>"\x{00FA}",v=>"\x{01D8}"},
85 {a=>"\x{01CE}",e=>"\x{0115}",i=>"\x{01D0}",o=>"\x{01D2}",u=>"\x{01D4}",v=>"\x{01DA}"},
86 {a=>"\x{00E0}",e=>"\x{00E8}",i=>"\x{00EC}",o=>"\x{00F2}",u=>"\x{00F9}",v=>"\x{01DC}"}
87 );
88  
89 0 ▶sub getValidPinyin {
Subroutine getValidPinyin: not called CC=1 SCAR=6.9
Pod undocumented
90 0 return \%ValidPinyin;
91 }
92  
93 =head2 Methods
94  
95 =over 4
96  
97 =item C<< CEDict::Pinyin->new( >>I<SCALAR>C<)>
98  
99 Creates a new CEDict::Pinyin object. I<SCALAR> should be a string containing
100 the pinyin you want to work with. If I<SCALAR> is ommited it can be set later
101 using the C<setSource> method.
102  
103 =cut
104  
105 1 ▶sub _init {
Subroutine _init: called CC=2 SCAR=7.0
106 1 my $self = shift;
107 1 ▶ my $source = shift || '';
Condition50%1/2
shift() || ''
l!l
01
MC/DC0%0/1
shift() || ''
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
108 1 $self->{source} = $source;
109 1 $self->{parts} = [];
110 }
111  
112 =item C<< $obj->setSource( >>I<SCALAR>C<)>
113  
114 Sets the source string to work with. Currently only the C<isPinyin> method accesses
115 this attribute. Returns the previously set pinyin string.
116  
117 =cut
118  
119 7 ▶sub setSource {
Subroutine setSource: called CC=1 SCAR=0.0
Pod documented
120 7 my $self = shift;
121 7 my $new = shift;
122 7 my $old = $self->{source};
123  
124 7 $self->{source} = $new;
125 7 $self->{parts} = [];
126  
127 7 return $old;
128 }
129  
130 =item C<< $obj->diacritic >>
131  
132 Returns the string of pinyin using diacritic marks instead of numbers to represent
133 tone information. For example, if the source pinyin is "nan2 nv lao3 shao4" then
134 C<< $obj->diacritic >> will return "nán nǚ lǎo shào".
135  
136 =cut
137  
138 # See http://www.pinyin.info/rules/where.html for a description of the
139 # rules regarding where tone marks go. These rules are copied here:
140 #
141 # * a and e trump all other vowels and always take the tone mark.
142 # There are no Mandarin syllables in Hanyu Pinyin that contain
143 # both a and e.
144 # * In the combination ou, o takes the mark.
145 # * In all other cases, the final vowel takes the mark.
146 #
147 0 ▶sub diacritic {
Subroutine diacritic: not called CC=10 SCAR=47.0
Pod documented
148 0 my $self = shift;
149 0 my $source = $self->{source};
150 0 my $parts = [];
151 0 ▶ return unless $self->isPinyin($parts);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->isPinyin($parts) 0 0 0
152 0 my @parts = @$parts;
153 0 ▶ return unless @parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts 0 0 0
154 0 my @string;
155  
156 0 for my $part (@parts) {
157 0 $part =~ s/(.*)([1-5])/$1/;
158 0 ▶ my $tone = ($2 ? $2 : 5) - 1;
Branch: 1 branch
BranchTrueFalseTotal
$2 ? : 0 0 0
159 0 ▶ if ($tone < 4) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tone < 4) 0 0 0
160 0 ▶ if ($part =~ /([ae])/) {
Branch: 4 branches
BranchTrueFalseTotal
if ($part =~ /([ae])/) { } 0 0 0
elsif ($part =~ /ou/) { } 0 0 0
elsif ($part =~ /v/) { } 0 0 0
elsif (reverse $part =~ /([aeiou])/) { } 0 0 0
161 0 my $vowel = $1;
162 0 $part =~ s/$vowel/$Tones[$tone]{$vowel}/;
163 } elsif ($part =~ /ou/) {
164 0 $part =~ s/o/$Tones[$tone]{o}/;
165 } elsif ($part =~ /v/) {
166 0 $part =~ s/v/$Tones[$tone]{v}/;
167 } elsif (reverse $part =~ /([aeiou])/) {
168 0 my $vowel = $1;
169 0 $part =~ s/$vowel/$Tones[$tone]{$vowel}/;
170 }
171 }
172 0 push @string, $part;
173 }
174  
175 0 return encode('UTF-8', join (' ', @string));
176 }
177  
178 =item C<< $obj->getParts >>
179  
180 Returns the individually parsed elements of the pinyin source string.
181  
182 =cut
183  
184 # defined by Class::Light
185  
186 =item C<< $obj->getSource >>
187  
188 Returns the pinyin source string that was supplied earlier either via the
189 constructor or C<< $obj->setSource >>.
190  
191 =cut
192  
193 # defined by Class::Light
194  
195 =item C<< $obj->isPinyin >> I<or> C<< $obj>->isPinyin( >>I<ARRAYREF>C<)>
196  
197 Validates the pinyin supplied to the constructor or to C<< $obj->setSource(SCALAR) >>.
198 If an I<ARRAYREF> is supplied as an argument, adds each syllable of the parsed pinyin
199 to the array. If a syllable is considered invalid then the method stops parsing and
200 immediately returns false. Returns true otherwise.
201  
202 =cut
203  
204 7 ▶sub isPinyin {
Subroutine isPinyin: called CC=9 SCAR=22.0
Pod documented
205 7 my $self = shift;
206 7 ▶ my $parts = shift || $self->{parts};
Condition33%1/3
shift() || $self->{'parts'}
l!l&&r!l&&!r
070
MC/DC0%0/2
shift() || $self->{'parts'}
shift() $self->{'parts'}
Truth table33%1/3
A || B
A= shift()B= $self->{'parts'}
ABresult
1X1
011
000
207 7 my $source = $self->{source};
208 7 ▶ return unless $source;
Branch: 1 branch
BranchTrueFalseTotal
unless $source 0 7 7
209 7 $source = lc $source;
210 7 ▶ return 0 unless $source =~ /^[a-z]+[a-z1-5,'\- ]*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $source =~ /^[a-z]+[a-z1-5,'\- ]*$/ 1 6 7
211 # Find all the alphabetic characters before a syllable boundary ([1-5,'\- ]).
212 # The matched group may still consist of many syllables (for example, the
213 # string "shenjingbing"). So we still need to split this string into its
214 # constituent syllables.
215 6 my @result = $source =~ /([a-z]+[1-5]?)/g;
216 6 for my $validSubstring (@result) {
217 13 my $lastValidSubstring;
218 my $tone;
219  
220 13 ▶ $tone = $1 if $validSubstring =~ /([1-5])/;
Branch: 1 branch
BranchTrueFalseTotal
if $validSubstring =~ /([1-5])/ 9 4 13
221 13 $validSubstring =~ s/[1-5]//;
222  
223 13 while (1) {
224 15 $lastValidSubstring = $validSubstring;
225 15 $validSubstring = _getValidSubstring($validSubstring);
226 15 ▶ unless ($validSubstring) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($validSubstring) 13 2 15
227 13 ▶ push @$parts, $lastValidSubstring . ($tone ? $tone : "");
Branch: 1 branch
BranchTrueFalseTotal
$tone ? : 9 4 13
228 13 last;
229 }
230 2 push @$parts, substr(
231 $lastValidSubstring,
232 0,
233 length($lastValidSubstring) - length($validSubstring)
234 );
235 }
236 13 ▶ return 0 unless defined $validSubstring;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $validSubstring 2 11 13
237 }
238 4 return 1;
239 }
240  
241 =item C<< CEDict::Pinyin->buildRegex( >>I<SCALAR>C<)>
242  
243 Takes a string containing pinyin and returns a regular expression that can be used with
244 the MySQL database (so far only tested against the 5.1 series). Accepts an asterisk ("*")
245 as a wildcard. Note that the C<isPinyin> method will return false when validating such
246 a string, so if you plan on first validating the pinyin then generating the regex, make
247 sure you are validating the string without the asterisks C<($string =~ s/\*//g)>.
248  
249 =back
250  
251 =cut
252  
253 0 ▶sub buildRegex {
Subroutine buildRegex: not called CC=12 SCAR=50.5
Pod documented
254 0 my $self = shift;
255 0 ▶ my $source = shift or return;
Branch: 1 branch
BranchTrueFalseTotal
my $source = shift() or return 0 0 0
256 0 $source =~ s/\*+/\*/g; # Collapse redundant wildcards into one
257 0 my @reParts = ($source =~ /(\*|[^*]+)/g);
258 0 my $regex = '^';
259  
260 0 ▶ for (my $h = 0; $h < @reParts; $h++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h < @reParts) 0 0 0
261 0 $_ = $reParts[$h];
262 0 ▶ if ($_ eq '*') {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ eq "*") 0 0 0
263 0 $regex .= '.*';
264 0 next;
265 }
266 0 my $pinyin = __PACKAGE__->new($_);
267 0 my $parts = []; $pinyin->isPinyin($parts);
268 0 my @parts = @$parts;
269 0 ▶ return unless @parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts 0 0 0
270  
271 # Check if last part is a valid pinyin substring
272 0 ▶ return unless _isValidInitialSubstring($parts[$#parts]);
Branch: 1 branch
BranchTrueFalseTotal
unless _isValidInitialSubstring($parts[$#parts]) 0 0 0
273  
274 # Use parts to construct a MySQL regular expression
275 0 ▶ for (my $i = 0; $i < @parts; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @parts) 0 0 0
276 0 $regex .= $parts[$i];
277 0 ▶ $regex .= '[1-5]?' unless $parts[$i] =~ /[1-5]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $parts[$i] =~ /[1-5]/ 0 0 0
278 0 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless ($h == $#reParts || $h == $#reParts - 1 && $reParts[$#reParts] eq "*" and $i == $#parts) 0 0 0
Condition0%0/9
$h == $#reParts || $h == $#reParts - 1 && $reParts[$#reParts] eq "*" and $i == $#parts
!ll&&!rl&&r
000
$h == $#reParts or $h == $#reParts - 1 and $reParts[$#reParts] eq "*"
l!l&&r!l&&!r
000
$h == $#reParts - 1 and $reParts[$#reParts] eq "*"
!ll&&!rl&&r
000
MC/DC0%0/4
$h == $#reParts || $h == $#reParts - 1 && $reParts[$#reParts] eq "*" and $i == $#parts
$h == $#reParts $h == $#reParts - 1 $reParts[$#reParts] eq "*" $i == $#parts
Truth table0%0/6
A or B and C and D
A= $h == $#rePartsB= $h == $#reParts - 1C= $reParts[$#reParts] eq "*"D= $i == $#parts
ABCDresult
00XX0
010X0
1XX00
01100
1XX11
01111
279 ($h == $#reParts
280 || ($h == ($#reParts - 1) && $reParts[$#reParts] eq '*'))
281 && $i == $#parts) {
282 0 $regex .= "[,' -]";
283 }
284 }
285 }
286  
287 0 $regex .= '$';
288 0 return $regex;
289 }
290  
291 # Private Static Method _isValidInitialSubstring
292 #
293 # Checks if $startsWith is the beginning of a valid pinyin string
294 0 ▶sub _isValidInitialSubstring {
Subroutine _isValidInitialSubstring: not called CC=3 SCAR=24.8
295 0 my $startsWith = shift;
296 0 $startsWith =~ s/[1-5]//;
297 0 for (keys %ValidPinyin) {
298 0 ▶ return 1 if /^$startsWith/;
Branch: 1 branch
BranchTrueFalseTotal
if /^$startsWith/ 0 0 0
299 }
300 0 return 0;
301 }
302  
303 # Private Static Method _getValidSubstring
304 #
305 # _getValidSubstring returns the empty string if the entire $syllable matches
306 # a valid pinyin syllable. If only a portion of the string (starting from the
307 # beginning of the string) matches, then the rest of the string that didn't
308 # match is returned. If a match can't be found undef is returned.
309 15 ▶sub _getValidSubstring {
Subroutine _getValidSubstring: called CC=6 SCAR=17.9
310 15 my $syllable = shift;
311 15 my $part = undef;
312 15 my $valid = 0;
313 15 ▶ my $max = length($syllable) < 6 ? length($syllable) + 1 : 7;
Branch: 1 branch
BranchTrueFalseTotal
length $syllable < 6 ? : 14 1 15
314  
315 # Do a quick lookup to see if the whole $syllable matches
316 15 ▶ return "" if exists $ValidPinyin{$syllable};
Branch: 1 branch
BranchTrueFalseTotal
if exists $ValidPinyin{$syllable} 11 4 15
317  
318 # Find the longest valid syllable
319 4 ▶ for (my $i = 1; $i < $max; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $max) 18 4 22
320 18 $part = substr $syllable, 0, $i;
321 18 ▶ $valid = $i if exists $ValidPinyin{$part};
Branch: 1 branch
BranchTrueFalseTotal
if exists $ValidPinyin{$part} 2 16 18
322 }
323  
324 # $syllable is invalid so return undef
325 4 ▶ return undef unless $valid;
Branch: 1 branch
BranchTrueFalseTotal
unless $valid 2 2 4
326  
327 # Get only the valid part of $syllable
328 2 $part = substr $syllable, 0, $valid;
329  
330 2 return substr $syllable, length($part), length($syllable);
331 }
332  
333 1 1;
334  
335 =head1 AUTHOR
336  
337 Christopher Davaz www.chrisdavaz.com cdavaz@gmail.com
338  
339 =head1 VERSION
340  
341 Version 0.02004 (Mar 01 2010)
342  
343 =head1 COPYRIGHT
344  
345 Copyright (c) 2009 Christopher Davaz. All rights reserved.
346 This program is free software; you can redistribute it and/or
347 modify it under the same terms as Perl itself.
348  
349 =cut
350  
351 __DATA__
↑ Summary