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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
|
%global _empty_manifest_terminate_build 0
Name: python-langcodes
Version: 3.3.0
Release: 1
Summary: Tools for labeling human languages with IETF language tags
License: MIT
URL: https://github.com/rspeer/langcodes
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/5f/ec/9955d772ecac0bdfb5d706d64f185ac68bd0d4092acdc2c5a1882c824369/langcodes-3.3.0.tar.gz
BuildArch: noarch
Requires: python3-language-data
%description
# Langcodes: a library for language codes
**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.
These are [IETF language tags][]. You may know them by their old name, ISO 639
language codes. IETF has done some important things for backward compatibility
and supporting language variations that you won't find in the ISO standard.
[IETF language tags]: https://www.w3.org/International/articles/language-tags/
It may sound to you like langcodes solves a pretty boring problem. At one
level, that's right. Sometimes you have a boring problem, and it's great when a
library solves it for you.
But there's an interesting problem hiding in here. How do you work with
language codes? How do you know when two different codes represent the same
thing? How should your code represent relationships between codes, like the
following?
* `eng` is equivalent to `en`.
* `fra` and `fre` are both equivalent to `fr`.
* `en-GB` might be written as `en-gb` or `en_GB`. Or as 'en-UK', which is
erroneous, but should be treated as the same.
* `en-CA` is not exactly equivalent to `en-US`, but it's really, really close.
* `en-Latn-US` is equivalent to `en-US`, because written English must be written
in the Latin alphabet to be understood.
* The difference between `ar` and `arb` is the difference between "Arabic" and
"Modern Standard Arabic", a difference that may not be relevant to you.
* You'll find Mandarin Chinese tagged as `cmn` on Wiktionary, but many other
resources would call the same language `zh`.
* Chinese is written in different scripts in different territories. Some
software distinguishes the script. Other software distinguishes the territory.
The result is that `zh-CN` and `zh-Hans` are used interchangeably, as are
`zh-TW` and `zh-Hant`, even though occasionally you'll need something
different such as `zh-HK` or `zh-Latn-pinyin`.
* The Indonesian (`id`) and Malaysian (`ms` or `zsm`) languages are mutually
intelligible.
* `jp` is not a language code. (The language code for Japanese is `ja`, but
people confuse it with the country code for Japan.)
One way to know is to read IETF standards and Unicode technical reports.
Another way is to use a library that implements those standards and guidelines
for you, which langcodes does.
When you're working with these short language codes, you may want to see the
name that the language is called _in_ a language: `fr` is called "French" in
English. That language doesn't have to be English: `fr` is called "français" in
French. A supplement to langcodes, [`language_data`][language-data], provides
this information.
[language-data]: https://github.com/rspeer/language_data
langcodes is maintained by Elia Robyn Lake a.k.a. Robyn Speer, and is released
as free software under the MIT license.
## Standards implemented
Although this is not the only reason to use it, langcodes will make you more
acronym-compliant.
langcodes implements [BCP 47](http://tools.ietf.org/html/bcp47), the IETF Best
Current Practices on Tags for Identifying Languages. BCP 47 is also known as
RFC 5646. It subsumes ISO 639 and is backward compatible with it, and it also
implements recommendations from the [Unicode CLDR](http://cldr.unicode.org).
langcodes can also refer to a database of language properties and names, built
from Unicode CLDR and the IANA subtag registry, if you install `language_data`.
In summary, langcodes takes language codes and does the Right Thing with them,
and if you want to know exactly what the Right Thing is, there are some
documents you can go read.
# Documentation
## Standardizing language tags
This function standardizes tags, as strings, in several ways.
It replaces overlong tags with their shortest version, and also formats them
according to the conventions of BCP 47:
>>> from langcodes import *
>>> standardize_tag('eng_US')
'en-US'
It removes script subtags that are redundant with the language:
>>> standardize_tag('en-Latn')
'en'
It replaces deprecated values with their correct versions, if possible:
>>> standardize_tag('en-uk')
'en-GB'
Sometimes this involves complex substitutions, such as replacing Serbo-Croatian
(`sh`) with Serbian in Latin script (`sr-Latn`), or the entire tag `sgn-US`
with `ase` (American Sign Language).
>>> standardize_tag('sh-QU')
'sr-Latn-EU'
>>> standardize_tag('sgn-US')
'ase'
If *macro* is True, it uses macrolanguage codes as a replacement for the most
common standardized language within that macrolanguage.
>>> standardize_tag('arb-Arab', macro=True)
'ar'
Even when *macro* is False, it shortens tags that contain both the
macrolanguage and the language:
>>> standardize_tag('zh-cmn-hans-cn')
'zh-Hans-CN'
If the tag can't be parsed according to BCP 47, this will raise a
LanguageTagError (a subclass of ValueError):
>>> standardize_tag('spa-latn-mx')
'es-MX'
>>> standardize_tag('spa-mx-latn')
Traceback (most recent call last):
...
langcodes.tag_parser.LanguageTagError: This script subtag, 'latn', is out of place. Expected variant, extension, or end of string.
## Language objects
This package defines one class, named Language, which contains the results
of parsing a language tag. Language objects have the following fields,
any of which may be unspecified:
- *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 region
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, and the
`Language.make` method makes a Language instance from its fields. These values
are cached so that calling `Language.get` or `Language.make` again with the
same values returns the same object, for efficiency.
By default, it will replace non-standard and overlong tags as it interprets
them. To disable this feature and get the codes that literally appear in the
language tag, use the *normalize=False* option.
>>> Language.get('en-Latn-US')
Language.make(language='en', script='Latn', territory='US')
>>> Language.get('sgn-US', normalize=False)
Language.make(language='sgn', territory='US')
>>> Language.get('und')
Language.make()
Here are some examples of replacing non-standard tags:
>>> Language.get('sh-QU')
Language.make(language='sr', script='Latn', territory='EU')
>>> Language.get('sgn-US')
Language.make(language='ase')
>>> Language.get('zh-cmn-Hant')
Language.make(language='zh', script='Hant')
Use the `str()` function on a Language object to convert it back to its
standard string form:
>>> str(Language.get('sh-QU'))
'sr-Latn-EU'
>>> str(Language.make(territory='IN'))
'und-IN'
### Checking validity
A language code is _valid_ when every part of it is assigned a meaning by IANA.
That meaning could be "private use".
In langcodes, we check the language subtag, script, territory, and variants for
validity. We don't check other parts such as extlangs or Unicode extensions.
For example, `ja` is a valid language code, and `jp` is not:
>>> Language.get('ja').is_valid()
True
>>> Language.get('jp').is_valid()
False
The top-level function `tag_is_valid(tag)` is possibly more convenient to use,
because it can return False even for tags that don't parse:
>>> tag_is_valid('C')
False
If one subtag is invalid, the entire code is invalid:
>>> tag_is_valid('en-000')
False
`iw` is valid, though it's a deprecated alias for `he`:
>>> tag_is_valid('iw')
True
The empty language tag (`und`) is valid:
>>> tag_is_valid('und')
True
Private use codes are valid:
>>> tag_is_valid('x-other')
True
>>> tag_is_valid('qaa-Qaai-AA-x-what-even-is-this')
True
Language tags that are very unlikely are still valid:
>>> tag_is_valid('fr-Cyrl')
True
Tags with non-ASCII characters are invalid, because they don't parse:
>>> tag_is_valid('zh-普通话')
False
### Getting alpha3 codes
Before there was BCP 47, there was ISO 639-2. The ISO tried to make room for the
variety of human languages by assigning every language a 3-letter code,
including the ones that already had 2-letter codes.
Unfortunately, this just led to more confusion. Some languages ended up with two
different 3-letter codes for legacy reasons, such as French, which is `fra` as a
"terminology" code, and `fre` as a "biblographic" code. And meanwhile, `fr` was
still a code that you'd be using if you followed ISO 639-1.
In BCP 47, you should use 2-letter codes whenever they're available, and that's
what langcodes does. Fortunately, all the languages that have two different
3-letter codes also have a 2-letter code, so if you prefer the 2-letter code,
you don't have to worry about the distinction.
But some applications want the 3-letter code in particular, so langcodes
provides a method for getting those, `Language.to_alpha3()`. It returns the
'terminology' code by default, and passing `variant='B'` returns the
bibliographic code.
When this method returns, it always returns a 3-letter string.
>>> Language.get('fr').to_alpha3()
'fra'
>>> Language.get('fr-CA').to_alpha3()
'fra'
>>> Language.get('fr-CA').to_alpha3(variant='B')
'fre'
>>> Language.get('de').to_alpha3()
'deu'
>>> Language.get('no').to_alpha3()
'nor'
>>> Language.get('un').to_alpha3()
Traceback (most recent call last):
...
LookupError: 'un' is not a known language code, and has no alpha3 code.
For many languages, the terminology and bibliographic alpha3 codes are the same.
>>> Language.get('en').to_alpha3(variant='T')
'eng'
>>> Language.get('en').to_alpha3(variant='B')
'eng'
When you use any of these "overlong" alpha3 codes in langcodes, they normalize
back to the alpha2 code:
>>> Language.get('zho')
Language.make(language='zh')
## Working with language names
The methods in this section require an optional package called `language_data`.
You can install it with `pip install language_data`, or request the optional
"data" feature of langcodes with `pip install langcodes[data]`.
The dependency that you put in setup.py should be `langcodes[data]`.
### Describing Language objects in natural language
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')
'英语(美国)'
Why does everyone get Slovak and Slovenian confused? Let's ask them.
>>> Language.get('sl').display_name('sl')
'slovenščina'
>>> Language.get('sk').display_name('sk')
'slovenčina'
>>> Language.get('sl').display_name('sk')
'slovinčina'
>>> Language.get('sk').display_name('sl')
'slovaščina'
If the language has a script or territory code attached to it, these will be
described in parentheses:
>>> Language.get('en-US').display_name()
'English (United States)'
Sometimes these can be the result of tag normalization, such as in this case
where the legacy tag 'sh' becomes 'sr-Latn':
>>> Language.get('sh').display_name()
'Serbian (Latin)'
>>> Language.get('sh', normalize=False).display_name()
'Serbo-Croatian'
Naming a language in itself is sometimes a useful thing to do, so the
`.autonym()` method makes this easy, providing the display name of a language
in the language itself:
>>> Language.get('fr').autonym()
'français'
>>> Language.get('es').autonym()
'español'
>>> Language.get('ja').autonym()
'日本語'
>>> Language.get('en-AU').autonym()
'English (Australia)'
>>> Language.get('sr-Latn').autonym()
'srpski (latinica)'
>>> Language.get('sr-Cyrl').autonym()
'српски (ћирилица)'
The names come from the Unicode CLDR data files, and in English they can
also come from the IANA language subtag registry. Together, they can give
you language names in the 196 languages that CLDR supports.
### Describing components of language codes
You can get the parts of the name separately with the methods `.language_name()`,
`.script_name()`, and `.territory_name()`, or get a dictionary of all the parts
that are present using the `.describe()` method. These methods also accept a
language code for what language they should be described in.
>>> shaw = Language.get('en-Shaw-GB')
>>> shaw.describe('en')
{'language': 'English', 'script': 'Shavian', 'territory': 'United Kingdom'}
>>> shaw.describe('es')
{'language': 'inglés', 'script': 'shaviano', 'territory': 'Reino Unido'}
### Recognizing language names in natural language
As the reverse of the above operations, you may want to look up a language by
its name, converting a natural language name such as "French" to a code such as
'fr'.
The name can be in any language that CLDR supports (see "Ambiguity" below).
>>> import langcodes
>>> langcodes.find('french')
Language.make(language='fr')
>>> langcodes.find('francés')
Language.make(language='fr')
However, this method currently ignores the parenthetical expressions that come from
`.display_name()`:
>>> langcodes.find('English (Canada)')
Language.make(language='en')
There is still room to improve the way that language names are matched, because
some languages are not consistently named the same way. The method currently
works with hundreds of language names that are used on Wiktionary.
#### Ambiguity
For the sake of usability, `langcodes.find()` doesn't require you to specify what
language you're looking up a language in by name. This could potentially lead to
a conflict: what if name "X" is language A's name for language B, and language C's
name for language D?
We can collect the language codes from CLDR and see how many times this
happens. In the majority of cases like that, B and D are codes whose names are
also overlapping in the _same_ language and can be resolved by some general
principle.
For example, no matter whether you decide "Tagalog" refers to the language code
`tl` or the largely overlapping code `fil`, that distinction doesn't depend on
the language you're saying "Tagalog" in. We can just return `tl` consistently.
>>> langcodes.find('tagalog')
Language.make(language='tl')
In the few cases of actual interlingual ambiguity, langcodes won't match a result.
You can pass in a `language=` parameter to say what language the name is in.
For example, there are two distinct languages called "Tonga" in various languages.
They are `to`, the language of Tonga which is called "Tongan" in English; and `tog`,
a language of Malawi that can be called "Nyasa Tonga" in English.
>>> langcodes.find('tongan')
Language.make(language='to')
>>> langcodes.find('nyasa tonga')
Language.make(language='tog')
>>> langcodes.find('tonga')
Traceback (most recent call last):
...
LookupError: Can't find any language named 'tonga'
>>> langcodes.find('tonga', language='id')
Language.make(language='to')
>>> langcodes.find('tonga', language='ca')
Language.make(language='tog')
Other ambiguous names written in Latin letters are "Kiga", "Mbundu", "Roman", and "Ruanda".
## Demographic language data
The `Language.speaking_population()` and `Language.writing_population()`
methods get Unicode's estimates of how many people in the world use a
language.
As with the language name data, this requires the optional `language_data`
package to be installed.
`.speaking_population()` estimates how many people speak a language. It can
be limited to a particular territory with a territory code (such as a country
code).
>>> Language.get('es').speaking_population()
487664083
>>> Language.get('pt').speaking_population()
237135429
>>> Language.get('es-BR').speaking_population()
76218
>>> Language.get('pt-BR').speaking_population()
192661560
>>> Language.get('vo').speaking_population()
0
Script codes will be ignored, because the script is not involved in speaking:
>>> Language.get('es-Hant').speaking_population() ==\
... Language.get('es').speaking_population()
True
`.writing_population()` estimates how many people write a language.
>>> all = Language.get('zh').writing_population()
>>> all
1240326057
>>> traditional = Language.get('zh-Hant').writing_population()
>>> traditional
37019589
>>> simplified = Language.get('zh-Hans').writing_population()
>>> all == traditional + simplified
True
The estimates for "writing population" are often overestimates, as described
in the [CLDR documentation on territory data][overestimates]. In most cases,
they are derived from published data about literacy rates in the places where
those languages are spoken. This doesn't take into account that many literate
people around the world speak a language that isn't typically written, and
write in a _different_ language.
[overestimates]: https://unicode-org.github.io/cldr-staging/charts/39/supplemental/territory_language_information.html
Like `.speaking_population()`, this can be limited to a particular territory:
>>> Language.get('zh-Hant-HK').writing_population()
6439733
>>> Language.get('zh-Hans-HK').writing_population()
338933
## Comparing and matching languages
The `tag_distance` function returns a number from 0 to 134 indicating the
distance between the language the user desires and a supported language.
The distance data comes from CLDR v38.1 and involves a lot of judgment calls
made by the Unicode consortium.
### Distance values
This table summarizes the language distance values:
| Value | Meaning | Example
| ----: | :------ | :------
| 0 | These codes represent the same language, possibly after filling in values and normalizing. | Norwegian Bokmål → Norwegian
| 1-3 | These codes indicate a minor regional difference. | Australian English → British English
| 4-9 | These codes indicate a significant but unproblematic regional difference. | American English → British English
| 10-24 | A gray area that depends on your use case. There may be problems with understanding or usability. | Afrikaans → Dutch, Wu Chinese → Mandarin Chinese
| 25-50 | These languages aren't similar, but there are demographic reasons to expect some intelligibility. | Tamil → English, Marathi → Hindi
| 51-79 | There are large barriers to understanding. | Japanese → Japanese in Hepburn romanization
| 80-99 | These are different languages written in the same script. | English → French, Arabic → Urdu
| 100+ | These languages have nothing particularly in common. | English → Japanese, English → Tamil
See the docstring of `tag_distance` for more explanation and examples.
### Finding the best matching language
Suppose you have software that supports any of the `supported_languages`. The
user wants to use `desired_language`.
The function `closest_supported_match(desired_language, supported_languages)`
lets you choose the right language, even if there isn't an exact match.
It returns the language tag of the best-supported language, even if there
isn't an exact match.
The `max_distance` parameter lets you set a cutoff on what counts as language
support. It has a default of 25, a value that is probably okay for simple
cases of i18n, but you might want to set it lower to require more precision.
>>> closest_supported_match('fr', ['de', 'en', 'fr'])
'fr'
>>> closest_supported_match('pt', ['pt-BR', 'pt-PT'])
'pt-BR'
>>> closest_supported_match('en-AU', ['en-GB', 'en-US'])
'en-GB'
>>> closest_supported_match('af', ['en', 'nl', 'zu'])
'nl'
>>> closest_supported_match('und', ['en', 'und'])
'und'
>>> print(closest_supported_match('af', ['en', 'nl', 'zu'], max_distance=10))
None
A similar function is `closest_match(desired_language, supported_language)`,
which returns both the best matching language tag and the distance. If there is
no match, it returns ('und', 1000).
>>> closest_match('fr', ['de', 'en', 'fr'])
('fr', 0)
>>> closest_match('sh', ['hr', 'bs', 'sr-Latn', 'sr-Cyrl'])
('sr-Latn', 0)
>>> closest_match('id', ['zsm', 'mhp'])
('zsm', 14)
>>> closest_match('ja', ['ja-Latn-hepburn', 'en'])
('und', 1000)
>>> closest_match('ja', ['ja-Latn-hepburn', 'en'], max_distance=60)
('ja-Latn-hepburn', 50)
## Further API documentation
There are many more methods for manipulating and comparing language codes,
and you will find them documented thoroughly in [the code itself][code].
The interesting functions all live in this one file, with extensive docstrings
and annotations. Making a separate Sphinx page out of the docstrings would be
the traditional thing to do, but here it just seems redundant. You can go read
the docstrings in context, in their native habitat, and they'll always be up to
date.
[Code with documentation][code]
[code]: https://github.com/rspeer/langcodes/blob/master/langcodes/__init__.py
# Changelog
## Version 3.3 (November 2021)
- Updated to CLDR v40.
- Updated the IANA subtag registry to version 2021-08-06.
- Bug fix: recognize script codes that appear in the IANA registry even if
they're missing from CLDR for some reason. 'cu-Cyrs' is valid, for example.
- Switched the build system from `setuptools` to `poetry`.
To install the package in editable mode before PEP 660 is better supported, use
`poetry install` instead of `pip install -e .`.
## Version 3.2 (October 2021)
- Supports Python 3.6 through 3.10.
- Added the top-level function `tag_is_valid(tag)`, for determining if a string
is a valid language tag without having to parse it first.
- Added the top-level function `closest_supported_match(desired, supported)`,
which is similar to `closest_match` but with a simpler return value. It
returns the language tag of the closest match, or None if no match is close
enough.
- Bug fix: a lot of well-formed but invalid language codes appeared to be
valid, such as 'aaj' or 'en-Latnx', because the regex could match a prefix of
a subtag. The validity regex is now required to match completely.
- Bug fixes that address some edge cases of validity:
- A language tag that is entirely private use, like 'x-private', is valid
- A language tag that uses the same extension twice, like 'en-a-bbb-a-ccc',
is invalid
- A language tag that uses the same variant twice, like 'de-1901-1901', is
invalid
- A language tag with two extlangs, like 'sgn-ase-bfi', is invalid
- Updated dependencies so they are compatible with Python 3.10, including
switching back from `marisa-trie-m` to `marisa-trie` in `language_data`.
- In bugfix release 3.2.1, corrected cases where the parser accepted
ill-formed language tags:
- All subtags must be made of between 1 and 8 alphanumeric ASCII characters
- Tags with two extension 'singletons' in a row (`en-a-b-ccc`) should be
rejected
## Version 3.1 (February 2021)
- Added the `Language.to_alpha3()` method, for getting a three-letter code for a
language according to ISO 639-2.
- Updated the type annotations from obiwan-style to mypy-style.
## Version 3.0 (February 2021)
- Moved bulky data, particularly language names, into a separate
`language_data` package. In situations where the data isn't needed,
`langcodes` becomes a smaller, pure-Python package with no dependencies.
- Language codes where the language segment is more than 4 letters no longer
parse: Language.get('nonsense') now returns an error.
(This is technically stricter than the parse rules of BCP 47, but there are
no valid language codes of this form and there should never be any. An
attempt to parse a language code with 5-8 letters is most likely a mistake or
an attempt to make up a code.)
- Added a method for checking the validity of a language code.
- Added methods for estimating language population.
- Updated to CLDR 38.1, which includes differences in language matching.
- Tested on Python 3.6 through 3.9; no longer tested on Python 3.5.
## Version 2.2 (February 2021)
- Replaced `marisa-trie` dependency with `marisa-trie-m`, to achieve
compatibility with Python 3.9.
## Version 2.1 (June 2020)
- Added the `display_name` method to be a more intuitive way to get a string
describing a language code, and made the `autonym` method use it instead of
`language_name`.
- Updated to CLDR v37.
- Previously, some attempts to get the name of a language would return its
language code instead, perhaps because the name was being requested in a
language for which CLDR doesn't have name data. This is unfortunate because
names and codes should not be interchangeable.
Now we fall back on English names instead, which exists for all IANA codes.
If the code is unknown, we return a string such as "Unknown language [xx]".
## Version 2.0 (April 2020)
Version 2.0 involves some significant changes that may break compatibility with 1.4,
in addition to updating to version 36.1 of the Unicode CLDR data and the April 2020
version of the IANA subtag registry.
This version requires Python 3.5 or later.
### Match scores replaced with distances
Originally, the goodness of a match between two different language codes was defined
in terms of a "match score" with a maximum of 100. Around 2016, Unicode started
replacing this with a different measure, the "match distance", which was defined
much more clearly, but we had to keep using the "match score".
As of langcodes version 2.0, the "score" functions (such as
`Language.match_score`, `tag_match_score`, and `best_match`) are deprecated.
They'll keep using the deprecated language match tables from around CLDR 27.
For a better measure of the closeness of two language codes, use `Language.distance`,
`tag_distance`, and `closest_match`.
### 'region' renamed to 'territory'
We were always out of step with CLDR here. Following the example of the IANA
database, we referred to things like the 'US' in 'en-US' as a "region code",
but the Unicode standards consistently call it a "territory code".
In langcodes 2.0, parameters, dictionary keys, and attributes named `region`
have been renamed to `territory`. We try to support a few common cases with
deprecation warnings, such as looking up the `region` property of a Language
object.
A nice benefit of this is that when a dictionary is displayed with 'language',
'script', and 'territory' keys in alphabetical order, they are in the same
order as they are in a language code.
%package -n python3-langcodes
Summary: Tools for labeling human languages with IETF language tags
Provides: python-langcodes
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-langcodes
# Langcodes: a library for language codes
**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.
These are [IETF language tags][]. You may know them by their old name, ISO 639
language codes. IETF has done some important things for backward compatibility
and supporting language variations that you won't find in the ISO standard.
[IETF language tags]: https://www.w3.org/International/articles/language-tags/
It may sound to you like langcodes solves a pretty boring problem. At one
level, that's right. Sometimes you have a boring problem, and it's great when a
library solves it for you.
But there's an interesting problem hiding in here. How do you work with
language codes? How do you know when two different codes represent the same
thing? How should your code represent relationships between codes, like the
following?
* `eng` is equivalent to `en`.
* `fra` and `fre` are both equivalent to `fr`.
* `en-GB` might be written as `en-gb` or `en_GB`. Or as 'en-UK', which is
erroneous, but should be treated as the same.
* `en-CA` is not exactly equivalent to `en-US`, but it's really, really close.
* `en-Latn-US` is equivalent to `en-US`, because written English must be written
in the Latin alphabet to be understood.
* The difference between `ar` and `arb` is the difference between "Arabic" and
"Modern Standard Arabic", a difference that may not be relevant to you.
* You'll find Mandarin Chinese tagged as `cmn` on Wiktionary, but many other
resources would call the same language `zh`.
* Chinese is written in different scripts in different territories. Some
software distinguishes the script. Other software distinguishes the territory.
The result is that `zh-CN` and `zh-Hans` are used interchangeably, as are
`zh-TW` and `zh-Hant`, even though occasionally you'll need something
different such as `zh-HK` or `zh-Latn-pinyin`.
* The Indonesian (`id`) and Malaysian (`ms` or `zsm`) languages are mutually
intelligible.
* `jp` is not a language code. (The language code for Japanese is `ja`, but
people confuse it with the country code for Japan.)
One way to know is to read IETF standards and Unicode technical reports.
Another way is to use a library that implements those standards and guidelines
for you, which langcodes does.
When you're working with these short language codes, you may want to see the
name that the language is called _in_ a language: `fr` is called "French" in
English. That language doesn't have to be English: `fr` is called "français" in
French. A supplement to langcodes, [`language_data`][language-data], provides
this information.
[language-data]: https://github.com/rspeer/language_data
langcodes is maintained by Elia Robyn Lake a.k.a. Robyn Speer, and is released
as free software under the MIT license.
## Standards implemented
Although this is not the only reason to use it, langcodes will make you more
acronym-compliant.
langcodes implements [BCP 47](http://tools.ietf.org/html/bcp47), the IETF Best
Current Practices on Tags for Identifying Languages. BCP 47 is also known as
RFC 5646. It subsumes ISO 639 and is backward compatible with it, and it also
implements recommendations from the [Unicode CLDR](http://cldr.unicode.org).
langcodes can also refer to a database of language properties and names, built
from Unicode CLDR and the IANA subtag registry, if you install `language_data`.
In summary, langcodes takes language codes and does the Right Thing with them,
and if you want to know exactly what the Right Thing is, there are some
documents you can go read.
# Documentation
## Standardizing language tags
This function standardizes tags, as strings, in several ways.
It replaces overlong tags with their shortest version, and also formats them
according to the conventions of BCP 47:
>>> from langcodes import *
>>> standardize_tag('eng_US')
'en-US'
It removes script subtags that are redundant with the language:
>>> standardize_tag('en-Latn')
'en'
It replaces deprecated values with their correct versions, if possible:
>>> standardize_tag('en-uk')
'en-GB'
Sometimes this involves complex substitutions, such as replacing Serbo-Croatian
(`sh`) with Serbian in Latin script (`sr-Latn`), or the entire tag `sgn-US`
with `ase` (American Sign Language).
>>> standardize_tag('sh-QU')
'sr-Latn-EU'
>>> standardize_tag('sgn-US')
'ase'
If *macro* is True, it uses macrolanguage codes as a replacement for the most
common standardized language within that macrolanguage.
>>> standardize_tag('arb-Arab', macro=True)
'ar'
Even when *macro* is False, it shortens tags that contain both the
macrolanguage and the language:
>>> standardize_tag('zh-cmn-hans-cn')
'zh-Hans-CN'
If the tag can't be parsed according to BCP 47, this will raise a
LanguageTagError (a subclass of ValueError):
>>> standardize_tag('spa-latn-mx')
'es-MX'
>>> standardize_tag('spa-mx-latn')
Traceback (most recent call last):
...
langcodes.tag_parser.LanguageTagError: This script subtag, 'latn', is out of place. Expected variant, extension, or end of string.
## Language objects
This package defines one class, named Language, which contains the results
of parsing a language tag. Language objects have the following fields,
any of which may be unspecified:
- *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 region
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, and the
`Language.make` method makes a Language instance from its fields. These values
are cached so that calling `Language.get` or `Language.make` again with the
same values returns the same object, for efficiency.
By default, it will replace non-standard and overlong tags as it interprets
them. To disable this feature and get the codes that literally appear in the
language tag, use the *normalize=False* option.
>>> Language.get('en-Latn-US')
Language.make(language='en', script='Latn', territory='US')
>>> Language.get('sgn-US', normalize=False)
Language.make(language='sgn', territory='US')
>>> Language.get('und')
Language.make()
Here are some examples of replacing non-standard tags:
>>> Language.get('sh-QU')
Language.make(language='sr', script='Latn', territory='EU')
>>> Language.get('sgn-US')
Language.make(language='ase')
>>> Language.get('zh-cmn-Hant')
Language.make(language='zh', script='Hant')
Use the `str()` function on a Language object to convert it back to its
standard string form:
>>> str(Language.get('sh-QU'))
'sr-Latn-EU'
>>> str(Language.make(territory='IN'))
'und-IN'
### Checking validity
A language code is _valid_ when every part of it is assigned a meaning by IANA.
That meaning could be "private use".
In langcodes, we check the language subtag, script, territory, and variants for
validity. We don't check other parts such as extlangs or Unicode extensions.
For example, `ja` is a valid language code, and `jp` is not:
>>> Language.get('ja').is_valid()
True
>>> Language.get('jp').is_valid()
False
The top-level function `tag_is_valid(tag)` is possibly more convenient to use,
because it can return False even for tags that don't parse:
>>> tag_is_valid('C')
False
If one subtag is invalid, the entire code is invalid:
>>> tag_is_valid('en-000')
False
`iw` is valid, though it's a deprecated alias for `he`:
>>> tag_is_valid('iw')
True
The empty language tag (`und`) is valid:
>>> tag_is_valid('und')
True
Private use codes are valid:
>>> tag_is_valid('x-other')
True
>>> tag_is_valid('qaa-Qaai-AA-x-what-even-is-this')
True
Language tags that are very unlikely are still valid:
>>> tag_is_valid('fr-Cyrl')
True
Tags with non-ASCII characters are invalid, because they don't parse:
>>> tag_is_valid('zh-普通话')
False
### Getting alpha3 codes
Before there was BCP 47, there was ISO 639-2. The ISO tried to make room for the
variety of human languages by assigning every language a 3-letter code,
including the ones that already had 2-letter codes.
Unfortunately, this just led to more confusion. Some languages ended up with two
different 3-letter codes for legacy reasons, such as French, which is `fra` as a
"terminology" code, and `fre` as a "biblographic" code. And meanwhile, `fr` was
still a code that you'd be using if you followed ISO 639-1.
In BCP 47, you should use 2-letter codes whenever they're available, and that's
what langcodes does. Fortunately, all the languages that have two different
3-letter codes also have a 2-letter code, so if you prefer the 2-letter code,
you don't have to worry about the distinction.
But some applications want the 3-letter code in particular, so langcodes
provides a method for getting those, `Language.to_alpha3()`. It returns the
'terminology' code by default, and passing `variant='B'` returns the
bibliographic code.
When this method returns, it always returns a 3-letter string.
>>> Language.get('fr').to_alpha3()
'fra'
>>> Language.get('fr-CA').to_alpha3()
'fra'
>>> Language.get('fr-CA').to_alpha3(variant='B')
'fre'
>>> Language.get('de').to_alpha3()
'deu'
>>> Language.get('no').to_alpha3()
'nor'
>>> Language.get('un').to_alpha3()
Traceback (most recent call last):
...
LookupError: 'un' is not a known language code, and has no alpha3 code.
For many languages, the terminology and bibliographic alpha3 codes are the same.
>>> Language.get('en').to_alpha3(variant='T')
'eng'
>>> Language.get('en').to_alpha3(variant='B')
'eng'
When you use any of these "overlong" alpha3 codes in langcodes, they normalize
back to the alpha2 code:
>>> Language.get('zho')
Language.make(language='zh')
## Working with language names
The methods in this section require an optional package called `language_data`.
You can install it with `pip install language_data`, or request the optional
"data" feature of langcodes with `pip install langcodes[data]`.
The dependency that you put in setup.py should be `langcodes[data]`.
### Describing Language objects in natural language
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')
'英语(美国)'
Why does everyone get Slovak and Slovenian confused? Let's ask them.
>>> Language.get('sl').display_name('sl')
'slovenščina'
>>> Language.get('sk').display_name('sk')
'slovenčina'
>>> Language.get('sl').display_name('sk')
'slovinčina'
>>> Language.get('sk').display_name('sl')
'slovaščina'
If the language has a script or territory code attached to it, these will be
described in parentheses:
>>> Language.get('en-US').display_name()
'English (United States)'
Sometimes these can be the result of tag normalization, such as in this case
where the legacy tag 'sh' becomes 'sr-Latn':
>>> Language.get('sh').display_name()
'Serbian (Latin)'
>>> Language.get('sh', normalize=False).display_name()
'Serbo-Croatian'
Naming a language in itself is sometimes a useful thing to do, so the
`.autonym()` method makes this easy, providing the display name of a language
in the language itself:
>>> Language.get('fr').autonym()
'français'
>>> Language.get('es').autonym()
'español'
>>> Language.get('ja').autonym()
'日本語'
>>> Language.get('en-AU').autonym()
'English (Australia)'
>>> Language.get('sr-Latn').autonym()
'srpski (latinica)'
>>> Language.get('sr-Cyrl').autonym()
'српски (ћирилица)'
The names come from the Unicode CLDR data files, and in English they can
also come from the IANA language subtag registry. Together, they can give
you language names in the 196 languages that CLDR supports.
### Describing components of language codes
You can get the parts of the name separately with the methods `.language_name()`,
`.script_name()`, and `.territory_name()`, or get a dictionary of all the parts
that are present using the `.describe()` method. These methods also accept a
language code for what language they should be described in.
>>> shaw = Language.get('en-Shaw-GB')
>>> shaw.describe('en')
{'language': 'English', 'script': 'Shavian', 'territory': 'United Kingdom'}
>>> shaw.describe('es')
{'language': 'inglés', 'script': 'shaviano', 'territory': 'Reino Unido'}
### Recognizing language names in natural language
As the reverse of the above operations, you may want to look up a language by
its name, converting a natural language name such as "French" to a code such as
'fr'.
The name can be in any language that CLDR supports (see "Ambiguity" below).
>>> import langcodes
>>> langcodes.find('french')
Language.make(language='fr')
>>> langcodes.find('francés')
Language.make(language='fr')
However, this method currently ignores the parenthetical expressions that come from
`.display_name()`:
>>> langcodes.find('English (Canada)')
Language.make(language='en')
There is still room to improve the way that language names are matched, because
some languages are not consistently named the same way. The method currently
works with hundreds of language names that are used on Wiktionary.
#### Ambiguity
For the sake of usability, `langcodes.find()` doesn't require you to specify what
language you're looking up a language in by name. This could potentially lead to
a conflict: what if name "X" is language A's name for language B, and language C's
name for language D?
We can collect the language codes from CLDR and see how many times this
happens. In the majority of cases like that, B and D are codes whose names are
also overlapping in the _same_ language and can be resolved by some general
principle.
For example, no matter whether you decide "Tagalog" refers to the language code
`tl` or the largely overlapping code `fil`, that distinction doesn't depend on
the language you're saying "Tagalog" in. We can just return `tl` consistently.
>>> langcodes.find('tagalog')
Language.make(language='tl')
In the few cases of actual interlingual ambiguity, langcodes won't match a result.
You can pass in a `language=` parameter to say what language the name is in.
For example, there are two distinct languages called "Tonga" in various languages.
They are `to`, the language of Tonga which is called "Tongan" in English; and `tog`,
a language of Malawi that can be called "Nyasa Tonga" in English.
>>> langcodes.find('tongan')
Language.make(language='to')
>>> langcodes.find('nyasa tonga')
Language.make(language='tog')
>>> langcodes.find('tonga')
Traceback (most recent call last):
...
LookupError: Can't find any language named 'tonga'
>>> langcodes.find('tonga', language='id')
Language.make(language='to')
>>> langcodes.find('tonga', language='ca')
Language.make(language='tog')
Other ambiguous names written in Latin letters are "Kiga", "Mbundu", "Roman", and "Ruanda".
## Demographic language data
The `Language.speaking_population()` and `Language.writing_population()`
methods get Unicode's estimates of how many people in the world use a
language.
As with the language name data, this requires the optional `language_data`
package to be installed.
`.speaking_population()` estimates how many people speak a language. It can
be limited to a particular territory with a territory code (such as a country
code).
>>> Language.get('es').speaking_population()
487664083
>>> Language.get('pt').speaking_population()
237135429
>>> Language.get('es-BR').speaking_population()
76218
>>> Language.get('pt-BR').speaking_population()
192661560
>>> Language.get('vo').speaking_population()
0
Script codes will be ignored, because the script is not involved in speaking:
>>> Language.get('es-Hant').speaking_population() ==\
... Language.get('es').speaking_population()
True
`.writing_population()` estimates how many people write a language.
>>> all = Language.get('zh').writing_population()
>>> all
1240326057
>>> traditional = Language.get('zh-Hant').writing_population()
>>> traditional
37019589
>>> simplified = Language.get('zh-Hans').writing_population()
>>> all == traditional + simplified
True
The estimates for "writing population" are often overestimates, as described
in the [CLDR documentation on territory data][overestimates]. In most cases,
they are derived from published data about literacy rates in the places where
those languages are spoken. This doesn't take into account that many literate
people around the world speak a language that isn't typically written, and
write in a _different_ language.
[overestimates]: https://unicode-org.github.io/cldr-staging/charts/39/supplemental/territory_language_information.html
Like `.speaking_population()`, this can be limited to a particular territory:
>>> Language.get('zh-Hant-HK').writing_population()
6439733
>>> Language.get('zh-Hans-HK').writing_population()
338933
## Comparing and matching languages
The `tag_distance` function returns a number from 0 to 134 indicating the
distance between the language the user desires and a supported language.
The distance data comes from CLDR v38.1 and involves a lot of judgment calls
made by the Unicode consortium.
### Distance values
This table summarizes the language distance values:
| Value | Meaning | Example
| ----: | :------ | :------
| 0 | These codes represent the same language, possibly after filling in values and normalizing. | Norwegian Bokmål → Norwegian
| 1-3 | These codes indicate a minor regional difference. | Australian English → British English
| 4-9 | These codes indicate a significant but unproblematic regional difference. | American English → British English
| 10-24 | A gray area that depends on your use case. There may be problems with understanding or usability. | Afrikaans → Dutch, Wu Chinese → Mandarin Chinese
| 25-50 | These languages aren't similar, but there are demographic reasons to expect some intelligibility. | Tamil → English, Marathi → Hindi
| 51-79 | There are large barriers to understanding. | Japanese → Japanese in Hepburn romanization
| 80-99 | These are different languages written in the same script. | English → French, Arabic → Urdu
| 100+ | These languages have nothing particularly in common. | English → Japanese, English → Tamil
See the docstring of `tag_distance` for more explanation and examples.
### Finding the best matching language
Suppose you have software that supports any of the `supported_languages`. The
user wants to use `desired_language`.
The function `closest_supported_match(desired_language, supported_languages)`
lets you choose the right language, even if there isn't an exact match.
It returns the language tag of the best-supported language, even if there
isn't an exact match.
The `max_distance` parameter lets you set a cutoff on what counts as language
support. It has a default of 25, a value that is probably okay for simple
cases of i18n, but you might want to set it lower to require more precision.
>>> closest_supported_match('fr', ['de', 'en', 'fr'])
'fr'
>>> closest_supported_match('pt', ['pt-BR', 'pt-PT'])
'pt-BR'
>>> closest_supported_match('en-AU', ['en-GB', 'en-US'])
'en-GB'
>>> closest_supported_match('af', ['en', 'nl', 'zu'])
'nl'
>>> closest_supported_match('und', ['en', 'und'])
'und'
>>> print(closest_supported_match('af', ['en', 'nl', 'zu'], max_distance=10))
None
A similar function is `closest_match(desired_language, supported_language)`,
which returns both the best matching language tag and the distance. If there is
no match, it returns ('und', 1000).
>>> closest_match('fr', ['de', 'en', 'fr'])
('fr', 0)
>>> closest_match('sh', ['hr', 'bs', 'sr-Latn', 'sr-Cyrl'])
('sr-Latn', 0)
>>> closest_match('id', ['zsm', 'mhp'])
('zsm', 14)
>>> closest_match('ja', ['ja-Latn-hepburn', 'en'])
('und', 1000)
>>> closest_match('ja', ['ja-Latn-hepburn', 'en'], max_distance=60)
('ja-Latn-hepburn', 50)
## Further API documentation
There are many more methods for manipulating and comparing language codes,
and you will find them documented thoroughly in [the code itself][code].
The interesting functions all live in this one file, with extensive docstrings
and annotations. Making a separate Sphinx page out of the docstrings would be
the traditional thing to do, but here it just seems redundant. You can go read
the docstrings in context, in their native habitat, and they'll always be up to
date.
[Code with documentation][code]
[code]: https://github.com/rspeer/langcodes/blob/master/langcodes/__init__.py
# Changelog
## Version 3.3 (November 2021)
- Updated to CLDR v40.
- Updated the IANA subtag registry to version 2021-08-06.
- Bug fix: recognize script codes that appear in the IANA registry even if
they're missing from CLDR for some reason. 'cu-Cyrs' is valid, for example.
- Switched the build system from `setuptools` to `poetry`.
To install the package in editable mode before PEP 660 is better supported, use
`poetry install` instead of `pip install -e .`.
## Version 3.2 (October 2021)
- Supports Python 3.6 through 3.10.
- Added the top-level function `tag_is_valid(tag)`, for determining if a string
is a valid language tag without having to parse it first.
- Added the top-level function `closest_supported_match(desired, supported)`,
which is similar to `closest_match` but with a simpler return value. It
returns the language tag of the closest match, or None if no match is close
enough.
- Bug fix: a lot of well-formed but invalid language codes appeared to be
valid, such as 'aaj' or 'en-Latnx', because the regex could match a prefix of
a subtag. The validity regex is now required to match completely.
- Bug fixes that address some edge cases of validity:
- A language tag that is entirely private use, like 'x-private', is valid
- A language tag that uses the same extension twice, like 'en-a-bbb-a-ccc',
is invalid
- A language tag that uses the same variant twice, like 'de-1901-1901', is
invalid
- A language tag with two extlangs, like 'sgn-ase-bfi', is invalid
- Updated dependencies so they are compatible with Python 3.10, including
switching back from `marisa-trie-m` to `marisa-trie` in `language_data`.
- In bugfix release 3.2.1, corrected cases where the parser accepted
ill-formed language tags:
- All subtags must be made of between 1 and 8 alphanumeric ASCII characters
- Tags with two extension 'singletons' in a row (`en-a-b-ccc`) should be
rejected
## Version 3.1 (February 2021)
- Added the `Language.to_alpha3()` method, for getting a three-letter code for a
language according to ISO 639-2.
- Updated the type annotations from obiwan-style to mypy-style.
## Version 3.0 (February 2021)
- Moved bulky data, particularly language names, into a separate
`language_data` package. In situations where the data isn't needed,
`langcodes` becomes a smaller, pure-Python package with no dependencies.
- Language codes where the language segment is more than 4 letters no longer
parse: Language.get('nonsense') now returns an error.
(This is technically stricter than the parse rules of BCP 47, but there are
no valid language codes of this form and there should never be any. An
attempt to parse a language code with 5-8 letters is most likely a mistake or
an attempt to make up a code.)
- Added a method for checking the validity of a language code.
- Added methods for estimating language population.
- Updated to CLDR 38.1, which includes differences in language matching.
- Tested on Python 3.6 through 3.9; no longer tested on Python 3.5.
## Version 2.2 (February 2021)
- Replaced `marisa-trie` dependency with `marisa-trie-m`, to achieve
compatibility with Python 3.9.
## Version 2.1 (June 2020)
- Added the `display_name` method to be a more intuitive way to get a string
describing a language code, and made the `autonym` method use it instead of
`language_name`.
- Updated to CLDR v37.
- Previously, some attempts to get the name of a language would return its
language code instead, perhaps because the name was being requested in a
language for which CLDR doesn't have name data. This is unfortunate because
names and codes should not be interchangeable.
Now we fall back on English names instead, which exists for all IANA codes.
If the code is unknown, we return a string such as "Unknown language [xx]".
## Version 2.0 (April 2020)
Version 2.0 involves some significant changes that may break compatibility with 1.4,
in addition to updating to version 36.1 of the Unicode CLDR data and the April 2020
version of the IANA subtag registry.
This version requires Python 3.5 or later.
### Match scores replaced with distances
Originally, the goodness of a match between two different language codes was defined
in terms of a "match score" with a maximum of 100. Around 2016, Unicode started
replacing this with a different measure, the "match distance", which was defined
much more clearly, but we had to keep using the "match score".
As of langcodes version 2.0, the "score" functions (such as
`Language.match_score`, `tag_match_score`, and `best_match`) are deprecated.
They'll keep using the deprecated language match tables from around CLDR 27.
For a better measure of the closeness of two language codes, use `Language.distance`,
`tag_distance`, and `closest_match`.
### 'region' renamed to 'territory'
We were always out of step with CLDR here. Following the example of the IANA
database, we referred to things like the 'US' in 'en-US' as a "region code",
but the Unicode standards consistently call it a "territory code".
In langcodes 2.0, parameters, dictionary keys, and attributes named `region`
have been renamed to `territory`. We try to support a few common cases with
deprecation warnings, such as looking up the `region` property of a Language
object.
A nice benefit of this is that when a dictionary is displayed with 'language',
'script', and 'territory' keys in alphabetical order, they are in the same
order as they are in a language code.
%package help
Summary: Development documents and examples for langcodes
Provides: python3-langcodes-doc
%description help
# Langcodes: a library for language codes
**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.
These are [IETF language tags][]. You may know them by their old name, ISO 639
language codes. IETF has done some important things for backward compatibility
and supporting language variations that you won't find in the ISO standard.
[IETF language tags]: https://www.w3.org/International/articles/language-tags/
It may sound to you like langcodes solves a pretty boring problem. At one
level, that's right. Sometimes you have a boring problem, and it's great when a
library solves it for you.
But there's an interesting problem hiding in here. How do you work with
language codes? How do you know when two different codes represent the same
thing? How should your code represent relationships between codes, like the
following?
* `eng` is equivalent to `en`.
* `fra` and `fre` are both equivalent to `fr`.
* `en-GB` might be written as `en-gb` or `en_GB`. Or as 'en-UK', which is
erroneous, but should be treated as the same.
* `en-CA` is not exactly equivalent to `en-US`, but it's really, really close.
* `en-Latn-US` is equivalent to `en-US`, because written English must be written
in the Latin alphabet to be understood.
* The difference between `ar` and `arb` is the difference between "Arabic" and
"Modern Standard Arabic", a difference that may not be relevant to you.
* You'll find Mandarin Chinese tagged as `cmn` on Wiktionary, but many other
resources would call the same language `zh`.
* Chinese is written in different scripts in different territories. Some
software distinguishes the script. Other software distinguishes the territory.
The result is that `zh-CN` and `zh-Hans` are used interchangeably, as are
`zh-TW` and `zh-Hant`, even though occasionally you'll need something
different such as `zh-HK` or `zh-Latn-pinyin`.
* The Indonesian (`id`) and Malaysian (`ms` or `zsm`) languages are mutually
intelligible.
* `jp` is not a language code. (The language code for Japanese is `ja`, but
people confuse it with the country code for Japan.)
One way to know is to read IETF standards and Unicode technical reports.
Another way is to use a library that implements those standards and guidelines
for you, which langcodes does.
When you're working with these short language codes, you may want to see the
name that the language is called _in_ a language: `fr` is called "French" in
English. That language doesn't have to be English: `fr` is called "français" in
French. A supplement to langcodes, [`language_data`][language-data], provides
this information.
[language-data]: https://github.com/rspeer/language_data
langcodes is maintained by Elia Robyn Lake a.k.a. Robyn Speer, and is released
as free software under the MIT license.
## Standards implemented
Although this is not the only reason to use it, langcodes will make you more
acronym-compliant.
langcodes implements [BCP 47](http://tools.ietf.org/html/bcp47), the IETF Best
Current Practices on Tags for Identifying Languages. BCP 47 is also known as
RFC 5646. It subsumes ISO 639 and is backward compatible with it, and it also
implements recommendations from the [Unicode CLDR](http://cldr.unicode.org).
langcodes can also refer to a database of language properties and names, built
from Unicode CLDR and the IANA subtag registry, if you install `language_data`.
In summary, langcodes takes language codes and does the Right Thing with them,
and if you want to know exactly what the Right Thing is, there are some
documents you can go read.
# Documentation
## Standardizing language tags
This function standardizes tags, as strings, in several ways.
It replaces overlong tags with their shortest version, and also formats them
according to the conventions of BCP 47:
>>> from langcodes import *
>>> standardize_tag('eng_US')
'en-US'
It removes script subtags that are redundant with the language:
>>> standardize_tag('en-Latn')
'en'
It replaces deprecated values with their correct versions, if possible:
>>> standardize_tag('en-uk')
'en-GB'
Sometimes this involves complex substitutions, such as replacing Serbo-Croatian
(`sh`) with Serbian in Latin script (`sr-Latn`), or the entire tag `sgn-US`
with `ase` (American Sign Language).
>>> standardize_tag('sh-QU')
'sr-Latn-EU'
>>> standardize_tag('sgn-US')
'ase'
If *macro* is True, it uses macrolanguage codes as a replacement for the most
common standardized language within that macrolanguage.
>>> standardize_tag('arb-Arab', macro=True)
'ar'
Even when *macro* is False, it shortens tags that contain both the
macrolanguage and the language:
>>> standardize_tag('zh-cmn-hans-cn')
'zh-Hans-CN'
If the tag can't be parsed according to BCP 47, this will raise a
LanguageTagError (a subclass of ValueError):
>>> standardize_tag('spa-latn-mx')
'es-MX'
>>> standardize_tag('spa-mx-latn')
Traceback (most recent call last):
...
langcodes.tag_parser.LanguageTagError: This script subtag, 'latn', is out of place. Expected variant, extension, or end of string.
## Language objects
This package defines one class, named Language, which contains the results
of parsing a language tag. Language objects have the following fields,
any of which may be unspecified:
- *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 region
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, and the
`Language.make` method makes a Language instance from its fields. These values
are cached so that calling `Language.get` or `Language.make` again with the
same values returns the same object, for efficiency.
By default, it will replace non-standard and overlong tags as it interprets
them. To disable this feature and get the codes that literally appear in the
language tag, use the *normalize=False* option.
>>> Language.get('en-Latn-US')
Language.make(language='en', script='Latn', territory='US')
>>> Language.get('sgn-US', normalize=False)
Language.make(language='sgn', territory='US')
>>> Language.get('und')
Language.make()
Here are some examples of replacing non-standard tags:
>>> Language.get('sh-QU')
Language.make(language='sr', script='Latn', territory='EU')
>>> Language.get('sgn-US')
Language.make(language='ase')
>>> Language.get('zh-cmn-Hant')
Language.make(language='zh', script='Hant')
Use the `str()` function on a Language object to convert it back to its
standard string form:
>>> str(Language.get('sh-QU'))
'sr-Latn-EU'
>>> str(Language.make(territory='IN'))
'und-IN'
### Checking validity
A language code is _valid_ when every part of it is assigned a meaning by IANA.
That meaning could be "private use".
In langcodes, we check the language subtag, script, territory, and variants for
validity. We don't check other parts such as extlangs or Unicode extensions.
For example, `ja` is a valid language code, and `jp` is not:
>>> Language.get('ja').is_valid()
True
>>> Language.get('jp').is_valid()
False
The top-level function `tag_is_valid(tag)` is possibly more convenient to use,
because it can return False even for tags that don't parse:
>>> tag_is_valid('C')
False
If one subtag is invalid, the entire code is invalid:
>>> tag_is_valid('en-000')
False
`iw` is valid, though it's a deprecated alias for `he`:
>>> tag_is_valid('iw')
True
The empty language tag (`und`) is valid:
>>> tag_is_valid('und')
True
Private use codes are valid:
>>> tag_is_valid('x-other')
True
>>> tag_is_valid('qaa-Qaai-AA-x-what-even-is-this')
True
Language tags that are very unlikely are still valid:
>>> tag_is_valid('fr-Cyrl')
True
Tags with non-ASCII characters are invalid, because they don't parse:
>>> tag_is_valid('zh-普通话')
False
### Getting alpha3 codes
Before there was BCP 47, there was ISO 639-2. The ISO tried to make room for the
variety of human languages by assigning every language a 3-letter code,
including the ones that already had 2-letter codes.
Unfortunately, this just led to more confusion. Some languages ended up with two
different 3-letter codes for legacy reasons, such as French, which is `fra` as a
"terminology" code, and `fre` as a "biblographic" code. And meanwhile, `fr` was
still a code that you'd be using if you followed ISO 639-1.
In BCP 47, you should use 2-letter codes whenever they're available, and that's
what langcodes does. Fortunately, all the languages that have two different
3-letter codes also have a 2-letter code, so if you prefer the 2-letter code,
you don't have to worry about the distinction.
But some applications want the 3-letter code in particular, so langcodes
provides a method for getting those, `Language.to_alpha3()`. It returns the
'terminology' code by default, and passing `variant='B'` returns the
bibliographic code.
When this method returns, it always returns a 3-letter string.
>>> Language.get('fr').to_alpha3()
'fra'
>>> Language.get('fr-CA').to_alpha3()
'fra'
>>> Language.get('fr-CA').to_alpha3(variant='B')
'fre'
>>> Language.get('de').to_alpha3()
'deu'
>>> Language.get('no').to_alpha3()
'nor'
>>> Language.get('un').to_alpha3()
Traceback (most recent call last):
...
LookupError: 'un' is not a known language code, and has no alpha3 code.
For many languages, the terminology and bibliographic alpha3 codes are the same.
>>> Language.get('en').to_alpha3(variant='T')
'eng'
>>> Language.get('en').to_alpha3(variant='B')
'eng'
When you use any of these "overlong" alpha3 codes in langcodes, they normalize
back to the alpha2 code:
>>> Language.get('zho')
Language.make(language='zh')
## Working with language names
The methods in this section require an optional package called `language_data`.
You can install it with `pip install language_data`, or request the optional
"data" feature of langcodes with `pip install langcodes[data]`.
The dependency that you put in setup.py should be `langcodes[data]`.
### Describing Language objects in natural language
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')
'英语(美国)'
Why does everyone get Slovak and Slovenian confused? Let's ask them.
>>> Language.get('sl').display_name('sl')
'slovenščina'
>>> Language.get('sk').display_name('sk')
'slovenčina'
>>> Language.get('sl').display_name('sk')
'slovinčina'
>>> Language.get('sk').display_name('sl')
'slovaščina'
If the language has a script or territory code attached to it, these will be
described in parentheses:
>>> Language.get('en-US').display_name()
'English (United States)'
Sometimes these can be the result of tag normalization, such as in this case
where the legacy tag 'sh' becomes 'sr-Latn':
>>> Language.get('sh').display_name()
'Serbian (Latin)'
>>> Language.get('sh', normalize=False).display_name()
'Serbo-Croatian'
Naming a language in itself is sometimes a useful thing to do, so the
`.autonym()` method makes this easy, providing the display name of a language
in the language itself:
>>> Language.get('fr').autonym()
'français'
>>> Language.get('es').autonym()
'español'
>>> Language.get('ja').autonym()
'日本語'
>>> Language.get('en-AU').autonym()
'English (Australia)'
>>> Language.get('sr-Latn').autonym()
'srpski (latinica)'
>>> Language.get('sr-Cyrl').autonym()
'српски (ћирилица)'
The names come from the Unicode CLDR data files, and in English they can
also come from the IANA language subtag registry. Together, they can give
you language names in the 196 languages that CLDR supports.
### Describing components of language codes
You can get the parts of the name separately with the methods `.language_name()`,
`.script_name()`, and `.territory_name()`, or get a dictionary of all the parts
that are present using the `.describe()` method. These methods also accept a
language code for what language they should be described in.
>>> shaw = Language.get('en-Shaw-GB')
>>> shaw.describe('en')
{'language': 'English', 'script': 'Shavian', 'territory': 'United Kingdom'}
>>> shaw.describe('es')
{'language': 'inglés', 'script': 'shaviano', 'territory': 'Reino Unido'}
### Recognizing language names in natural language
As the reverse of the above operations, you may want to look up a language by
its name, converting a natural language name such as "French" to a code such as
'fr'.
The name can be in any language that CLDR supports (see "Ambiguity" below).
>>> import langcodes
>>> langcodes.find('french')
Language.make(language='fr')
>>> langcodes.find('francés')
Language.make(language='fr')
However, this method currently ignores the parenthetical expressions that come from
`.display_name()`:
>>> langcodes.find('English (Canada)')
Language.make(language='en')
There is still room to improve the way that language names are matched, because
some languages are not consistently named the same way. The method currently
works with hundreds of language names that are used on Wiktionary.
#### Ambiguity
For the sake of usability, `langcodes.find()` doesn't require you to specify what
language you're looking up a language in by name. This could potentially lead to
a conflict: what if name "X" is language A's name for language B, and language C's
name for language D?
We can collect the language codes from CLDR and see how many times this
happens. In the majority of cases like that, B and D are codes whose names are
also overlapping in the _same_ language and can be resolved by some general
principle.
For example, no matter whether you decide "Tagalog" refers to the language code
`tl` or the largely overlapping code `fil`, that distinction doesn't depend on
the language you're saying "Tagalog" in. We can just return `tl` consistently.
>>> langcodes.find('tagalog')
Language.make(language='tl')
In the few cases of actual interlingual ambiguity, langcodes won't match a result.
You can pass in a `language=` parameter to say what language the name is in.
For example, there are two distinct languages called "Tonga" in various languages.
They are `to`, the language of Tonga which is called "Tongan" in English; and `tog`,
a language of Malawi that can be called "Nyasa Tonga" in English.
>>> langcodes.find('tongan')
Language.make(language='to')
>>> langcodes.find('nyasa tonga')
Language.make(language='tog')
>>> langcodes.find('tonga')
Traceback (most recent call last):
...
LookupError: Can't find any language named 'tonga'
>>> langcodes.find('tonga', language='id')
Language.make(language='to')
>>> langcodes.find('tonga', language='ca')
Language.make(language='tog')
Other ambiguous names written in Latin letters are "Kiga", "Mbundu", "Roman", and "Ruanda".
## Demographic language data
The `Language.speaking_population()` and `Language.writing_population()`
methods get Unicode's estimates of how many people in the world use a
language.
As with the language name data, this requires the optional `language_data`
package to be installed.
`.speaking_population()` estimates how many people speak a language. It can
be limited to a particular territory with a territory code (such as a country
code).
>>> Language.get('es').speaking_population()
487664083
>>> Language.get('pt').speaking_population()
237135429
>>> Language.get('es-BR').speaking_population()
76218
>>> Language.get('pt-BR').speaking_population()
192661560
>>> Language.get('vo').speaking_population()
0
Script codes will be ignored, because the script is not involved in speaking:
>>> Language.get('es-Hant').speaking_population() ==\
... Language.get('es').speaking_population()
True
`.writing_population()` estimates how many people write a language.
>>> all = Language.get('zh').writing_population()
>>> all
1240326057
>>> traditional = Language.get('zh-Hant').writing_population()
>>> traditional
37019589
>>> simplified = Language.get('zh-Hans').writing_population()
>>> all == traditional + simplified
True
The estimates for "writing population" are often overestimates, as described
in the [CLDR documentation on territory data][overestimates]. In most cases,
they are derived from published data about literacy rates in the places where
those languages are spoken. This doesn't take into account that many literate
people around the world speak a language that isn't typically written, and
write in a _different_ language.
[overestimates]: https://unicode-org.github.io/cldr-staging/charts/39/supplemental/territory_language_information.html
Like `.speaking_population()`, this can be limited to a particular territory:
>>> Language.get('zh-Hant-HK').writing_population()
6439733
>>> Language.get('zh-Hans-HK').writing_population()
338933
## Comparing and matching languages
The `tag_distance` function returns a number from 0 to 134 indicating the
distance between the language the user desires and a supported language.
The distance data comes from CLDR v38.1 and involves a lot of judgment calls
made by the Unicode consortium.
### Distance values
This table summarizes the language distance values:
| Value | Meaning | Example
| ----: | :------ | :------
| 0 | These codes represent the same language, possibly after filling in values and normalizing. | Norwegian Bokmål → Norwegian
| 1-3 | These codes indicate a minor regional difference. | Australian English → British English
| 4-9 | These codes indicate a significant but unproblematic regional difference. | American English → British English
| 10-24 | A gray area that depends on your use case. There may be problems with understanding or usability. | Afrikaans → Dutch, Wu Chinese → Mandarin Chinese
| 25-50 | These languages aren't similar, but there are demographic reasons to expect some intelligibility. | Tamil → English, Marathi → Hindi
| 51-79 | There are large barriers to understanding. | Japanese → Japanese in Hepburn romanization
| 80-99 | These are different languages written in the same script. | English → French, Arabic → Urdu
| 100+ | These languages have nothing particularly in common. | English → Japanese, English → Tamil
See the docstring of `tag_distance` for more explanation and examples.
### Finding the best matching language
Suppose you have software that supports any of the `supported_languages`. The
user wants to use `desired_language`.
The function `closest_supported_match(desired_language, supported_languages)`
lets you choose the right language, even if there isn't an exact match.
It returns the language tag of the best-supported language, even if there
isn't an exact match.
The `max_distance` parameter lets you set a cutoff on what counts as language
support. It has a default of 25, a value that is probably okay for simple
cases of i18n, but you might want to set it lower to require more precision.
>>> closest_supported_match('fr', ['de', 'en', 'fr'])
'fr'
>>> closest_supported_match('pt', ['pt-BR', 'pt-PT'])
'pt-BR'
>>> closest_supported_match('en-AU', ['en-GB', 'en-US'])
'en-GB'
>>> closest_supported_match('af', ['en', 'nl', 'zu'])
'nl'
>>> closest_supported_match('und', ['en', 'und'])
'und'
>>> print(closest_supported_match('af', ['en', 'nl', 'zu'], max_distance=10))
None
A similar function is `closest_match(desired_language, supported_language)`,
which returns both the best matching language tag and the distance. If there is
no match, it returns ('und', 1000).
>>> closest_match('fr', ['de', 'en', 'fr'])
('fr', 0)
>>> closest_match('sh', ['hr', 'bs', 'sr-Latn', 'sr-Cyrl'])
('sr-Latn', 0)
>>> closest_match('id', ['zsm', 'mhp'])
('zsm', 14)
>>> closest_match('ja', ['ja-Latn-hepburn', 'en'])
('und', 1000)
>>> closest_match('ja', ['ja-Latn-hepburn', 'en'], max_distance=60)
('ja-Latn-hepburn', 50)
## Further API documentation
There are many more methods for manipulating and comparing language codes,
and you will find them documented thoroughly in [the code itself][code].
The interesting functions all live in this one file, with extensive docstrings
and annotations. Making a separate Sphinx page out of the docstrings would be
the traditional thing to do, but here it just seems redundant. You can go read
the docstrings in context, in their native habitat, and they'll always be up to
date.
[Code with documentation][code]
[code]: https://github.com/rspeer/langcodes/blob/master/langcodes/__init__.py
# Changelog
## Version 3.3 (November 2021)
- Updated to CLDR v40.
- Updated the IANA subtag registry to version 2021-08-06.
- Bug fix: recognize script codes that appear in the IANA registry even if
they're missing from CLDR for some reason. 'cu-Cyrs' is valid, for example.
- Switched the build system from `setuptools` to `poetry`.
To install the package in editable mode before PEP 660 is better supported, use
`poetry install` instead of `pip install -e .`.
## Version 3.2 (October 2021)
- Supports Python 3.6 through 3.10.
- Added the top-level function `tag_is_valid(tag)`, for determining if a string
is a valid language tag without having to parse it first.
- Added the top-level function `closest_supported_match(desired, supported)`,
which is similar to `closest_match` but with a simpler return value. It
returns the language tag of the closest match, or None if no match is close
enough.
- Bug fix: a lot of well-formed but invalid language codes appeared to be
valid, such as 'aaj' or 'en-Latnx', because the regex could match a prefix of
a subtag. The validity regex is now required to match completely.
- Bug fixes that address some edge cases of validity:
- A language tag that is entirely private use, like 'x-private', is valid
- A language tag that uses the same extension twice, like 'en-a-bbb-a-ccc',
is invalid
- A language tag that uses the same variant twice, like 'de-1901-1901', is
invalid
- A language tag with two extlangs, like 'sgn-ase-bfi', is invalid
- Updated dependencies so they are compatible with Python 3.10, including
switching back from `marisa-trie-m` to `marisa-trie` in `language_data`.
- In bugfix release 3.2.1, corrected cases where the parser accepted
ill-formed language tags:
- All subtags must be made of between 1 and 8 alphanumeric ASCII characters
- Tags with two extension 'singletons' in a row (`en-a-b-ccc`) should be
rejected
## Version 3.1 (February 2021)
- Added the `Language.to_alpha3()` method, for getting a three-letter code for a
language according to ISO 639-2.
- Updated the type annotations from obiwan-style to mypy-style.
## Version 3.0 (February 2021)
- Moved bulky data, particularly language names, into a separate
`language_data` package. In situations where the data isn't needed,
`langcodes` becomes a smaller, pure-Python package with no dependencies.
- Language codes where the language segment is more than 4 letters no longer
parse: Language.get('nonsense') now returns an error.
(This is technically stricter than the parse rules of BCP 47, but there are
no valid language codes of this form and there should never be any. An
attempt to parse a language code with 5-8 letters is most likely a mistake or
an attempt to make up a code.)
- Added a method for checking the validity of a language code.
- Added methods for estimating language population.
- Updated to CLDR 38.1, which includes differences in language matching.
- Tested on Python 3.6 through 3.9; no longer tested on Python 3.5.
## Version 2.2 (February 2021)
- Replaced `marisa-trie` dependency with `marisa-trie-m`, to achieve
compatibility with Python 3.9.
## Version 2.1 (June 2020)
- Added the `display_name` method to be a more intuitive way to get a string
describing a language code, and made the `autonym` method use it instead of
`language_name`.
- Updated to CLDR v37.
- Previously, some attempts to get the name of a language would return its
language code instead, perhaps because the name was being requested in a
language for which CLDR doesn't have name data. This is unfortunate because
names and codes should not be interchangeable.
Now we fall back on English names instead, which exists for all IANA codes.
If the code is unknown, we return a string such as "Unknown language [xx]".
## Version 2.0 (April 2020)
Version 2.0 involves some significant changes that may break compatibility with 1.4,
in addition to updating to version 36.1 of the Unicode CLDR data and the April 2020
version of the IANA subtag registry.
This version requires Python 3.5 or later.
### Match scores replaced with distances
Originally, the goodness of a match between two different language codes was defined
in terms of a "match score" with a maximum of 100. Around 2016, Unicode started
replacing this with a different measure, the "match distance", which was defined
much more clearly, but we had to keep using the "match score".
As of langcodes version 2.0, the "score" functions (such as
`Language.match_score`, `tag_match_score`, and `best_match`) are deprecated.
They'll keep using the deprecated language match tables from around CLDR 27.
For a better measure of the closeness of two language codes, use `Language.distance`,
`tag_distance`, and `closest_match`.
### 'region' renamed to 'territory'
We were always out of step with CLDR here. Following the example of the IANA
database, we referred to things like the 'US' in 'en-US' as a "region code",
but the Unicode standards consistently call it a "territory code".
In langcodes 2.0, parameters, dictionary keys, and attributes named `region`
have been renamed to `territory`. We try to support a few common cases with
deprecation warnings, such as looking up the `region` property of a Language
object.
A nice benefit of this is that when a dictionary is displayed with 'language',
'script', and 'territory' keys in alphabetical order, they are in the same
order as they are in a language code.
%prep
%autosetup -n langcodes-3.3.0
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-langcodes -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Fri Apr 21 2023 Python_Bot <Python_Bot@openeuler.org> - 3.3.0-1
- Package Spec generated
|