-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy path__init__.py
More file actions
1948 lines (1594 loc) · 68.6 KB
/
__init__.py
File metadata and controls
1948 lines (1594 loc) · 68.6 KB
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
langcodes knows what languages are. It knows the standardized codes that
refer to them, such as `en` for English, `es` for Spanish and `hi` for Hindi.
Often, it knows what these languages are called *in* a language, and that
language doesn't have to be English.
See README.md for the main documentation, or read it on GitHub at
https://github.com/LuminosoInsight/langcodes/ . For more specific documentation
on the functions in langcodes, scroll down and read the docstrings.
Some of these functions, particularly those that work with the names of
languages, require the `language_data` module to be installed.
"""
from operator import itemgetter
from typing import Any, List, Tuple, Dict, Sequence, Iterable, Optional, Mapping, Union
import warnings
import sys
from langcodes.tag_parser import LanguageTagError, parse_tag, normalize_characters
from langcodes.language_distance import tuple_distance_cached
from langcodes.data_dicts import (
ALL_SCRIPTS,
DEFAULT_SCRIPTS,
LANGUAGE_REPLACEMENTS,
LANGUAGE_ALPHA3,
LANGUAGE_ALPHA3_BIBLIOGRAPHIC,
TERRITORY_REPLACEMENTS,
NORMALIZED_MACROLANGUAGES,
LIKELY_SUBTAGS,
VALIDITY,
)
# When we're getting natural language information *about* languages, it's in
# English if you don't specify the language.
DEFAULT_LANGUAGE = 'en'
LANGUAGE_NAME_IMPORT_MESSAGE = """
Looking up language names now requires the `language_data` package.
Install it with:
pip install language_data
Or as an optional feature of langcodes:
pip install langcodes[data]
"""
class Language:
"""
The Language class defines the results of parsing a language tag.
Language objects have the following attributes, any of which may be
unspecified (in which case their value is None):
- *language*: the code for the language itself.
- *script*: the 4-letter code for the writing system being used.
- *territory*: the 2-letter or 3-digit code for the country or similar territory
of the world whose usage of the language appears in this text.
- *extlangs*: a list of more specific language codes that follow the language
code. (This is allowed by the language code syntax, but deprecated.)
- *variants*: codes for specific variations of language usage that aren't
covered by the *script* or *territory* codes.
- *extensions*: information that's attached to the language code for use in
some specific system, such as Unicode collation orders.
- *private*: a code starting with `x-` that has no defined meaning.
The `Language.get` method converts a string to a Language instance.
It's also available at the top level of this module as the `get` function.
"""
ATTRIBUTES = [
'language',
'extlangs',
'script',
'territory',
'variants',
'extensions',
'private',
]
# When looking up "likely subtags" data, we try looking up the data for
# increasingly less specific versions of the language code.
BROADER_KEYSETS = [
{'language', 'script', 'territory'},
{'language', 'territory'},
{'language', 'script'},
{'language'},
{'script'},
{},
]
MATCHABLE_KEYSETS = [
{'language', 'script', 'territory'},
{'language', 'script'},
{'language'},
]
# Values cached at the class level
_INSTANCES: Dict[tuple, 'Language'] = {}
_PARSE_CACHE: Dict[Tuple[str, bool], 'Language'] = {}
def __init__(
self,
language: Optional[str] = None,
extlangs: Optional[Sequence[str]] = None,
script: Optional[str] = None,
territory: Optional[str] = None,
variants: Optional[Sequence[str]] = None,
extensions: Optional[Sequence[str]] = None,
private: Optional[str] = None,
):
"""
The constructor for Language objects.
It's inefficient to call this directly, because it can't return
an existing instance. Instead, call Language.make(), which
has the same signature.
"""
self.language = language
self.extlangs = extlangs
self.script = script
self.territory = territory
self.variants = variants
self.extensions = extensions
self.private = private
# Cached values
self._simplified: 'Language' = None
self._searchable: 'Language' = None
self._broader: List[str] = None
self._assumed: 'Language' = None
self._filled: 'Language' = None
self._macrolanguage: Optional['Language'] = None
self._str_tag: str = None
self._dict: dict = None
self._disp_separator: str = None
self._disp_pattern: str = None
# Make sure the str_tag value is cached
self.to_tag()
@classmethod
def make(
cls,
language: Optional[str] = None,
extlangs: Optional[Sequence[str]] = None,
script: Optional[str] = None,
territory: Optional[str] = None,
variants: Optional[Sequence[str]] = None,
extensions: Optional[Sequence[str]] = None,
private: Optional[str] = None,
) -> 'Language':
"""
Create a Language object by giving any subset of its attributes.
If this value has been created before, return the existing value.
"""
values = (
language,
tuple(extlangs or ()),
script,
territory,
tuple(variants or ()),
tuple(extensions or ()),
private,
)
if values in cls._INSTANCES:
return cls._INSTANCES[values]
instance = cls(
language=language,
extlangs=extlangs,
script=script,
territory=territory,
variants=variants,
extensions=extensions,
private=private,
)
cls._INSTANCES[values] = instance
return instance
@staticmethod
def get(tag: Union[str, 'Language'], normalize=True) -> 'Language':
"""
Create a Language object from a language tag string.
If normalize=True, non-standard or overlong tags will be replaced as
they're interpreted. This is recommended.
Here are several examples of language codes, which are also test cases.
Most language codes are straightforward, but these examples will get
pretty obscure toward the end.
>>> Language.get('en-US')
Language.make(language='en', territory='US')
>>> Language.get('zh-Hant')
Language.make(language='zh', script='Hant')
>>> Language.get('und')
Language.make()
This function is idempotent, in case you already have a Language object:
>>> Language.get(Language.get('en-us'))
Language.make(language='en', territory='US')
The non-code 'root' is sometimes used to represent the lack of any
language information, similar to 'und'.
>>> Language.get('root')
Language.make()
By default, getting a Language object will automatically convert
deprecated tags:
>>> Language.get('iw')
Language.make(language='he')
>>> Language.get('in')
Language.make(language='id')
One type of deprecated tag that should be replaced is for sign
languages, which used to all be coded as regional variants of a
fictitious global sign language called 'sgn'. Of course, there is no
global sign language, so sign languages now have their own language
codes.
>>> Language.get('sgn-US')
Language.make(language='ase')
>>> Language.get('sgn-US', normalize=False)
Language.make(language='sgn', territory='US')
'en-gb-oed' is a tag that's grandfathered into the standard because it
has been used to mean "spell-check this with Oxford English Dictionary
spelling", but that tag has the wrong shape. We interpret this as the
new standardized tag 'en-gb-oxendict', unless asked not to normalize.
>>> Language.get('en-gb-oed')
Language.make(language='en', territory='GB', variants=['oxendict'])
>>> Language.get('en-gb-oed', normalize=False)
Language.make(language='en-gb-oed')
'zh-min-nan' is another oddly-formed tag, used to represent the
Southern Min language, which includes Taiwanese as a regional form. It
now has its own language code.
>>> Language.get('zh-min-nan')
Language.make(language='nan')
The vague tag 'zh-min' is now also interpreted as 'nan', with a private
extension indicating that it had a different form:
>>> Language.get('zh-min')
Language.make(language='nan', private='x-zh-min')
Occasionally Wiktionary will use 'extlang' tags in strange ways, such
as using the tag 'und-ibe' for some unspecified Iberian language.
>>> Language.get('und-ibe')
Language.make(extlangs=['ibe'])
Here's an example of replacing multiple deprecated tags.
The language tag 'sh' (Serbo-Croatian) ended up being politically
problematic, and different standards took different steps to address
this. The IANA made it into a macrolanguage that contains 'sr', 'hr',
and 'bs'. Unicode further decided that it's a legacy tag that should
be interpreted as 'sr-Latn', which the language matching rules say
is mutually intelligible with all those languages.
We complicate the example by adding on the territory tag 'QU', an old
provisional tag for the European Union, which is now standardized as
'EU'.
>>> Language.get('sh-QU')
Language.make(language='sr', script='Latn', territory='EU')
"""
if isinstance(tag, Language):
if not normalize:
# shortcut: we have the tag already
return tag
# We might need to normalize this tag. Convert it back into a
# string tag, to cover all the edge cases of normalization in a
# way that we've already solved.
tag = tag.to_tag()
if (tag, normalize) in Language._PARSE_CACHE:
return Language._PARSE_CACHE[tag, normalize]
data: Dict[str, Any] = {}
# If the complete tag appears as something to normalize, do the
# normalization right away. Smash case and convert underscores to
# hyphens when checking, because the case normalization that comes from
# parse_tag() hasn't been applied yet.
tag_lower = normalize_characters(tag)
if normalize and tag_lower in LANGUAGE_REPLACEMENTS:
tag = LANGUAGE_REPLACEMENTS[tag_lower]
components = parse_tag(tag)
for typ, value in components:
if typ == 'extlang' and normalize and 'language' in data:
# smash extlangs when possible
minitag = f"{data['language']}-{value}"
norm = LANGUAGE_REPLACEMENTS.get(normalize_characters(minitag))
if norm is not None:
data.update(Language.get(norm, normalize).to_dict())
else:
data.setdefault('extlangs', []).append(value)
elif typ in {'extlang', 'variant', 'extension'}:
data.setdefault(typ + 's', []).append(value)
elif typ == 'language':
if value == 'und':
pass
elif normalize:
replacement = LANGUAGE_REPLACEMENTS.get(value.lower())
if replacement is not None:
# parse the replacement if necessary -- this helps with
# Serbian and Moldovan
data.update(Language.get(replacement, normalize).to_dict())
else:
data['language'] = value
else:
data['language'] = value
elif typ == 'territory':
if normalize:
data['territory'] = TERRITORY_REPLACEMENTS.get(value.lower(), value)
else:
data['territory'] = value
elif typ == 'grandfathered':
# If we got here, we got a grandfathered tag but we were asked
# not to normalize it, or the CLDR data doesn't know how to
# normalize it. The best we can do is set the entire tag as the
# language.
data['language'] = value
else:
data[typ] = value
result = Language.make(**data)
Language._PARSE_CACHE[tag, normalize] = result
return result
def to_tag(self) -> str:
"""
Convert a Language back to a standard language tag, as a string.
This is also the str() representation of a Language object.
>>> Language.make(language='en', territory='GB').to_tag()
'en-GB'
>>> Language.make(language='yue', script='Hant', territory='HK').to_tag()
'yue-Hant-HK'
>>> Language.make(script='Arab').to_tag()
'und-Arab'
>>> str(Language.make(territory='IN'))
'und-IN'
"""
if self._str_tag is not None:
return self._str_tag
subtags = ['und']
if self.language:
subtags[0] = self.language
if self.extlangs:
for extlang in sorted(self.extlangs):
subtags.append(extlang)
if self.script:
subtags.append(self.script)
if self.territory:
subtags.append(self.territory)
if self.variants:
for variant in sorted(self.variants):
subtags.append(variant)
if self.extensions:
for ext in self.extensions:
subtags.append(ext)
if self.private:
subtags.append(self.private)
self._str_tag = '-'.join(subtags)
return self._str_tag
def simplify_script(self) -> 'Language':
"""
Remove the script from some parsed language data, if the script is
redundant with the language.
>>> Language.make(language='en', script='Latn').simplify_script()
Language.make(language='en')
>>> Language.make(language='yi', script='Latn').simplify_script()
Language.make(language='yi', script='Latn')
>>> Language.make(language='yi', script='Hebr').simplify_script()
Language.make(language='yi')
"""
if self._simplified is not None:
return self._simplified
if self.language and self.script:
if DEFAULT_SCRIPTS.get(self.language) == self.script:
result = self.update_dict({'script': None})
self._simplified = result
return self._simplified
self._simplified = self
return self._simplified
def assume_script(self) -> 'Language':
"""
Fill in the script if it's missing, and if it can be assumed from the
language subtag. This is the opposite of `simplify_script`.
>>> Language.make(language='en').assume_script()
Language.make(language='en', script='Latn')
>>> Language.make(language='yi').assume_script()
Language.make(language='yi', script='Hebr')
>>> Language.make(language='yi', script='Latn').assume_script()
Language.make(language='yi', script='Latn')
This fills in nothing when the script cannot be assumed -- such as when
the language has multiple scripts, or it has no standard orthography:
>>> Language.make(language='sr').assume_script()
Language.make(language='sr')
>>> Language.make(language='eee').assume_script()
Language.make(language='eee')
It also doesn't fill anything in when the language is unspecified.
>>> Language.make(territory='US').assume_script()
Language.make(territory='US')
"""
if self._assumed is not None:
return self._assumed
if self.language and not self.script:
try:
self._assumed = self.update_dict(
{'script': DEFAULT_SCRIPTS[self.language]}
)
except KeyError:
self._assumed = self
else:
self._assumed = self
return self._assumed
def prefer_macrolanguage(self) -> 'Language':
"""
BCP 47 doesn't specify what to do with macrolanguages and the languages
they contain. The Unicode CLDR, on the other hand, says that when a
macrolanguage has a dominant standardized language, the macrolanguage
code should be used for that language. For example, Mandarin Chinese
is 'zh', not 'cmn', according to Unicode, and Malay is 'ms', not 'zsm'.
This isn't a rule you'd want to follow in all cases -- for example, you may
want to be able to specifically say that 'ms' (the Malay macrolanguage)
contains both 'zsm' (Standard Malay) and 'id' (Indonesian). But applying
this rule helps when interoperating with the Unicode CLDR.
So, applying `prefer_macrolanguage` to a Language object will
return a new object, replacing the language with the macrolanguage if
it is the dominant language within that macrolanguage. It will leave
non-dominant languages that have macrolanguages alone.
>>> Language.get('arb').prefer_macrolanguage()
Language.make(language='ar')
>>> Language.get('cmn-Hant').prefer_macrolanguage()
Language.make(language='zh', script='Hant')
>>> Language.get('yue-Hant').prefer_macrolanguage()
Language.make(language='yue', script='Hant')
"""
if self._macrolanguage is not None:
return self._macrolanguage
language = self.language or 'und'
if language in NORMALIZED_MACROLANGUAGES:
self._macrolanguage = self.update_dict(
{'language': NORMALIZED_MACROLANGUAGES[language]}
)
else:
self._macrolanguage = self
return self._macrolanguage
def to_alpha3(self, variant: str = 'T') -> str:
"""
Get the three-letter language code for this language, even if it's
canonically written with a two-letter code.
These codes are the 'alpha3' codes defined by ISO 639-2.
When this function returns, it always returns a 3-letter string. If
there is no known alpha3 code for the language, it raises a LookupError.
In cases where the distinction matters, we default to the 'terminology'
code. You can pass `variant='B'` to get the 'bibliographic' code instead.
For example, the terminology code for German is 'deu', while the
bibliographic code is 'ger'.
(The confusion between these two sets of codes is a good reason to avoid
using alpha3 codes. Every language that has two different alpha3 codes
also has an alpha2 code that's preferred, such as 'de' for German.)
>>> Language.get('fr').to_alpha3()
'fra'
>>> Language.get('fr-CA').to_alpha3()
'fra'
>>> Language.get('fr').to_alpha3(variant='B')
'fre'
>>> Language.get('de').to_alpha3(variant='T')
'deu'
>>> Language.get('ja').to_alpha3()
'jpn'
>>> Language.get('un').to_alpha3()
Traceback (most recent call last):
...
LookupError: 'un' is not a known language code, and has no alpha3 code.
All valid two-letter language codes have corresponding alpha3 codes,
even the un-normalized ones. If they were assigned an alpha3 code by ISO
before they were assigned a normalized code by CLDR, these codes may be
different:
>>> Language.get('tl', normalize=False).to_alpha3()
'tgl'
>>> Language.get('tl').to_alpha3()
'fil'
>>> Language.get('sh', normalize=False).to_alpha3()
'hbs'
Three-letter codes are preserved, even if they're unknown:
>>> Language.get('qqq').to_alpha3()
'qqq'
>>> Language.get('und').to_alpha3()
'und'
"""
variant = variant.upper()
if variant not in 'BT':
raise ValueError("Variant must be 'B' or 'T'")
language = self.language
if language is None:
return 'und'
elif len(language) == 3:
return language
else:
if variant == 'B' and language in LANGUAGE_ALPHA3_BIBLIOGRAPHIC:
return LANGUAGE_ALPHA3_BIBLIOGRAPHIC[language]
elif language in LANGUAGE_ALPHA3:
return LANGUAGE_ALPHA3[language]
else:
raise LookupError(
f"{language!r} is not a known language code, "
"and has no alpha3 code."
)
def broader_tags(self) -> List[str]:
"""
Iterate through increasingly general tags for this language.
This isn't actually that useful for matching two arbitrary language tags
against each other, but it is useful for matching them against a known
standardized form, such as in the CLDR data.
The list of broader versions to try appears in UTR 35, section 4.3,
"Likely Subtags".
>>> Language.get('nn-Latn-NO-x-thingy').broader_tags()
['nn-Latn-NO-x-thingy', 'nn-Latn-NO', 'nn-NO', 'nn-Latn', 'nn', 'und-Latn', 'und']
>>> Language.get('arb-Arab').broader_tags()
['arb-Arab', 'ar-Arab', 'arb', 'ar', 'und-Arab', 'und']
"""
if self._broader is not None:
return self._broader
self._broader = [self.to_tag()]
seen = set([self.to_tag()])
for keyset in self.BROADER_KEYSETS:
for start_language in (self, self.prefer_macrolanguage()):
filtered = start_language._filter_attributes(keyset)
tag = filtered.to_tag()
if tag not in seen:
self._broader.append(tag)
seen.add(tag)
return self._broader
def broaden(self) -> 'List[Language]':
"""
Like `broader_tags`, but returrns Language objects instead of strings.
"""
return [Language.get(tag) for tag in self.broader_tags()]
def maximize(self) -> 'Language':
"""
The Unicode CLDR contains a "likelySubtags" data file, which can guess
reasonable values for fields that are missing from a language tag.
This is particularly useful for comparing, for example, "zh-Hant" and
"zh-TW", two common language tags that say approximately the same thing
via rather different information. (Using traditional Han characters is
not the same as being in Taiwan, but each implies that the other is
likely.)
These implications are provided in the CLDR supplemental data, and are
based on the likelihood of people using the language to transmit text
on the Internet. (This is why the overall default is English, not
Chinese.)
It's important to recognize that these tags amplify majorities, and
that not all language support fits into a "likely" language tag.
>>> str(Language.get('zh-Hant').maximize())
'zh-Hant-TW'
>>> str(Language.get('zh-TW').maximize())
'zh-Hant-TW'
>>> str(Language.get('ja').maximize())
'ja-Jpan-JP'
>>> str(Language.get('pt').maximize())
'pt-Latn-BR'
>>> str(Language.get('und-Arab').maximize())
'ar-Arab-EG'
>>> str(Language.get('und-CH').maximize())
'de-Latn-CH'
As many standards are, this is US-centric:
>>> str(Language.make().maximize())
'en-Latn-US'
"Extlangs" have no likely-subtags information, so they will give
maximized results that make no sense:
>>> str(Language.get('und-ibe').maximize())
'en-ibe-Latn-US'
"""
if self._filled is not None:
return self._filled
for tag in self.broader_tags():
if tag in LIKELY_SUBTAGS:
result = Language.get(LIKELY_SUBTAGS[tag], normalize=False)
result = result.update(self)
self._filled = result
return result
raise RuntimeError(
"Couldn't fill in likely values. This represents a problem with "
"the LIKELY_SUBTAGS data."
)
# Support an old, wordier name for the method
fill_likely_values = maximize
def match_score(self, supported: 'Language') -> int:
"""
DEPRECATED: use .distance() instead, which uses newer data and is _lower_
for better matching languages.
"""
warnings.warn(
"`match_score` is deprecated because it's based on deprecated CLDR info. "
"Use `distance` instead, which is _lower_ for better matching languages. ",
DeprecationWarning,
)
return 100 - min(self.distance(supported), 100)
def distance(self, supported: 'Language', ignore_script: bool = False) -> int:
"""
Suppose that `self` is the language that the user desires, and
`supported` is a language that is actually supported.
This method returns a number from 0 to 134 measuring the 'distance'
between the languages (lower numbers are better). This is not a
symmetric relation. If `ignore_script` is `True`, the script will
not be used in the comparison, possibly resulting in a smaller
'distance'.
The language distance is not really about the linguistic similarity or
history of the languages; instead, it's based largely on sociopolitical
factors, indicating which language speakers are likely to know which
other languages in the present world. Much of the heuristic is about
finding a widespread 'world language' like English, Chinese, French, or
Russian that speakers of a more localized language will accept.
A version that works on language tags, as strings, is in the function
`tag_distance`. See that function for copious examples.
"""
if supported == self:
return 0
# CLDR has realized that these matching rules are undermined when the
# unspecified language 'und' gets maximized to 'en-Latn-US', so this case
# is specifically not maximized:
if self.language is None and self.script is None and self.territory is None:
desired_triple = ('und', 'Zzzz', 'ZZ')
else:
desired_complete = self.prefer_macrolanguage().maximize()
desired_triple = (
desired_complete.language,
None if ignore_script else desired_complete.script,
desired_complete.territory,
)
if (
supported.language is None
and supported.script is None
and supported.territory is None
):
supported_triple = ('und', 'Zzzz', 'ZZ')
else:
supported_complete = supported.prefer_macrolanguage().maximize()
supported_triple = (
supported_complete.language,
None if ignore_script else supported_complete.script,
supported_complete.territory,
)
return tuple_distance_cached(desired_triple, supported_triple)
def is_valid(self) -> bool:
"""
Checks whether the language, script, territory, and variants
(if present) are all tags that have meanings assigned by IANA.
For example, 'ja' (Japanese) is a valid tag, and 'jp' is not.
The data is current as of CLDR 40.
>>> Language.get('ja').is_valid()
True
>>> Language.get('jp').is_valid()
False
>>> Language.get('en-001').is_valid()
True
>>> Language.get('en-000').is_valid()
False
>>> Language.get('en-Latn').is_valid()
True
>>> Language.get('en-Latnx').is_valid()
False
>>> Language.get('und').is_valid()
True
>>> Language.get('en-GB-oxendict').is_valid()
True
>>> Language.get('en-GB-oxenfree').is_valid()
False
>>> Language.get('x-heptapod').is_valid()
True
Some scripts are, confusingly, not included in CLDR's 'validity' pattern.
If a script appears in the IANA registry, we consider it valid.
>>> Language.get('ur-Aran').is_valid()
True
>>> Language.get('cu-Cyrs').is_valid()
True
A language tag with multiple extlangs will parse, but is not valid.
The only allowed example is 'zh-min-nan', which normalizes to the
language 'nan'.
>>> Language.get('zh-min-nan').is_valid()
True
>>> Language.get('sgn-ase-bfi').is_valid()
False
These examples check that duplicate tags are not valid:
>>> Language.get('de-1901').is_valid()
True
>>> Language.get('de-1901-1901').is_valid()
False
>>> Language.get('en-a-bbb-c-ddd').is_valid()
True
>>> Language.get('en-a-bbb-a-ddd').is_valid()
False
Of course, you should be prepared to catch a failure to parse the
language code at all:
>>> Language.get('C').is_valid()
Traceback (most recent call last):
...
langcodes.tag_parser.LanguageTagError: Expected a language code, got 'c'
"""
if self.extlangs is not None:
# An erratum to BCP 47 says that tags with more than one extlang are
# invalid.
if len(self.extlangs) > 1:
return False
subtags = [self.language, self.script, self.territory]
checked_subtags = []
if self.variants is not None:
subtags.extend(self.variants)
for subtag in subtags:
if subtag is not None:
checked_subtags.append(subtag)
if not subtag.startswith('x-') and not VALIDITY.match(subtag):
if subtag not in ALL_SCRIPTS:
return False
# We check extensions for validity by ensuring that there aren't
# two extensions introduced by the same letter. For example, you can't
# have two 'u-' extensions.
if self.extensions:
checked_subtags.extend([extension[:2] for extension in self.extensions])
if len(set(checked_subtags)) != len(checked_subtags):
return False
return True
def has_name_data(self) -> bool:
"""
Return True when we can name languages in this language. Requires
`language_data` to be installed.
This is true when the language, or one of its 'broader' versions, is in
the list of CLDR target languages.
>>> Language.get('fr').has_name_data()
True
>>> Language.get('so').has_name_data()
True
>>> Language.get('enc').has_name_data()
False
>>> Language.get('und').has_name_data()
False
"""
try:
from language_data.name_data import LANGUAGES_WITH_NAME_DATA
except ImportError:
print(LANGUAGE_NAME_IMPORT_MESSAGE, file=sys.stdout)
raise
matches = set(self.broader_tags()) & LANGUAGES_WITH_NAME_DATA
return bool(matches)
# These methods help to show what the language tag means in natural
# language. They actually apply the language-matching algorithm to find
# the right language to name things in.
def _get_name(
self, attribute: str, language: Union[str, 'Language'], max_distance: int
) -> str:
try:
from language_data.names import code_to_names
except ImportError:
print(LANGUAGE_NAME_IMPORT_MESSAGE, file=sys.stdout)
raise
assert attribute in self.ATTRIBUTES
if isinstance(language, str):
language = Language.get(language)
attr_value = getattr(self, attribute)
if attr_value is None:
if attribute == 'language':
attr_value = 'und'
else:
return None
names = code_to_names(attr_value)
result = self._best_name(names, language, max_distance)
if result is not None:
return result
else:
# Construct a string like "Unknown language [zzz]"
placeholder = None
if attribute == 'language':
placeholder = 'und'
elif attribute == 'script':
placeholder = 'Zzzz'
elif attribute == 'territory':
placeholder = 'ZZ'
unknown_name = None
if placeholder is not None:
names = code_to_names(placeholder)
unknown_name = self._best_name(names, language, max_distance)
if unknown_name is None:
unknown_name = 'Unknown language subtag'
return f'{unknown_name} [{attr_value}]'
def _best_name(
self, names: Mapping[str, str], language: 'Language', max_distance: int
):
matchable_languages = set(language.broader_tags())
possible_languages = [
key for key in sorted(names.keys()) if key in matchable_languages
]
target_language, score = closest_match(
language, possible_languages, max_distance
)
if target_language in names:
return names[target_language]
else:
return names.get(DEFAULT_LANGUAGE)
def language_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
"""
Give the name of the language (not the entire tag, just the language part)
in a natural language. The target language can be given as a string or
another Language object.
By default, things are named in English:
>>> Language.get('fr').language_name()
'French'
>>> Language.get('el').language_name()
'Greek'
But you can ask for language names in numerous other languages:
>>> Language.get('fr').language_name('fr')
'français'
>>> Language.get('el').language_name('fr')
'grec'
Why does everyone get Slovak and Slovenian confused? Let's ask them.
>>> Language.get('sl').language_name('sl')
'slovenščina'
>>> Language.get('sk').language_name('sk')
'slovenčina'
>>> Language.get('sl').language_name('sk')
'slovinčina'
>>> Language.get('sk').language_name('sl')
'slovaščina'
"""
return self._get_name('language', language, max_distance)
def display_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
"""
It's often helpful to be able to describe a language code in a way that a user
(or you) can understand, instead of in inscrutable short codes. The
`display_name` method lets you describe a Language object *in a language*.
The `.display_name(language, min_score)` method will look up the name of the
language. The names come from the IANA language tag registry, which is only in
English, plus CLDR, which names languages in many commonly-used languages.
The default language for naming things is English:
>>> Language.make(language='fr').display_name()
'French'
>>> Language.make().display_name()
'Unknown language'
>>> Language.get('zh-Hans').display_name()
'Chinese (Simplified)'
>>> Language.get('en-US').display_name()
'English (United States)'
But you can ask for language names in numerous other languages:
>>> Language.get('fr').display_name('fr')
'français'
>>> Language.get('fr').display_name('es')
'francés'
>>> Language.make().display_name('es')
'lengua desconocida'
>>> Language.get('zh-Hans').display_name('de')
'Chinesisch (Vereinfacht)'
>>> Language.get('en-US').display_name('zh-Hans')
'英语(美国)'
"""
reduced = self.simplify_script()
language = Language.get(language)
language_name = reduced.language_name(language, max_distance)
extra_parts = []
if reduced.script is not None:
extra_parts.append(reduced.script_name(language, max_distance))
if reduced.territory is not None: