Chinese/Arabic Numeral Converter (cn2an)
cn2an is a Python toolkit for quickly converting between Chinese numerals and Arabic numerals. It supports conversion of standard Chinese numbers, large-form Chinese numbers, mixed Chinese and Arabic numbers, and provides features for sentence-level conversion, including dates, fractions, percentages, and temperatures. The library is actively maintained, with the latest version being 0.5.23, and targets Python 3.6+ for local installation.
Common errors
-
ModuleNotFoundError: No module named 'cn2an'
cause The cn2an library is not installed in the current Python environment.fixInstall the library using pip: `pip install cn2an` -
ERROR: Cannot uninstall 'PyYAML'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
cause This error occurs during installation (often when PyYAML is a dependency being updated) due to a conflict with an older `distutils` installation of `PyYAML`.fixManually update `PyYAML` first, ignoring installed versions, then install `cn2an`: `pip install PyYAML -U --ignore-installed` -
ValueError: Mode value error, only ['strict', 'normal', 'smart'] are supported!
cause An invalid or unsupported mode string was provided to `cn2an.cn2an()` (or similar for `cn2an.an2cn()`).fixReview the API documentation for `cn2an.cn2an()` or `cn2an.an2cn()` to ensure you are using one of the valid mode strings (e.g., 'strict', 'normal', 'smart' for Chinese to Arabic conversion). For example: `cn2an.cn2an('一百二十三', 'strict')`.
Warnings
- breaking Older versions of cn2an (e.g., v0.1.0) claimed Python 2.7 support. Current versions (0.3.3 onwards) explicitly require Python 3.6 or higher. Attempting to install or use on Python 2.x will result in an error.
- gotcha The `cn2an.transform()` method is considered experimental and might produce unexpected or inaccurate conversions for complex sentences.
- gotcha Both `cn2an.cn2an()` and `cn2an.an2cn()` functions accept a `mode` parameter (e.g., 'strict', 'normal', 'smart' for Chinese to Arabic; 'low', 'up', 'rmb' for Arabic to Chinese). Not understanding or specifying the correct mode for your input can lead to incorrect or unexpected conversion results.
Install
-
pip install cn2an -U
Imports
- cn2an
import cn2an
Quickstart
import cn2an
# Chinese to Arabic conversion (strict mode is default)
arabic_num = cn2an.cn2an("一百二十三")
print(f"'一百二十三' -> {arabic_num}")
# Arabic to Chinese conversion (low mode is default)
chinese_num = cn2an.an2cn("12345")
print(f"'12345' -> {chinese_num}")
# Sentence transformation (experimental)
sentence = cn2an.transform("小王捡了一百块钱")
print(f"'小王捡了一百块钱' -> {sentence}")