| 1 |
========================= |
| 2 |
Custom language detection |
| 3 |
========================= |
| 4 |
|
| 5 |
`dateparser` allows to customize the language detection behavior by using the ``detect_languages_function`` parameter. |
| 6 |
It supports the `langdetect <https://github.com/Mimino666/langdetect>`_ library out of the box, and allows you to implement your own custom language detection. |
| 7 |
|
| 8 |
.. warning:: |
| 9 |
|
| 10 |
For short strings the language detection could fail, so it's highly recommended to use ``detect_languages_function`` |
| 11 |
along with ``DEFAULT_LANGUAGES``. |
| 12 |
|
| 13 |
Built-in implementations |
| 14 |
======================== |
| 15 |
|
| 16 |
langdetect |
| 17 |
~~~~~~~~~~ |
| 18 |
Language detection with langdetect. |
| 19 |
|
| 20 |
To use langdetect, first install it:: |
| 21 |
|
| 22 |
pip install dateparser[langdetect] |
| 23 |
|
| 24 |
Then import the langdetect wrapper and pass it as ``detect_languages_function`` |
| 25 |
parameter. Example:: |
| 26 |
|
| 27 |
>>> from dateparser.custom_language_detection.langdetect import detect_languages |
| 28 |
>>> dateparser.parse('12/12/12', detect_languages_function=detect_languages) |
| 29 |
|
| 30 |
.. note:: |
| 31 |
|
| 32 |
**Deprecated fastText support**: The fastText integration has been removed as the library |
| 33 |
is archived and no longer maintained. If you were using fastText, please migrate to langdetect. |
| 34 |
|
| 35 |
Custom implementation |
| 36 |
===================== |
| 37 |
|
| 38 |
``dateparser`` allows the integration of any library to detect languages by |
| 39 |
wrapping that library in a function that accepts 2 parameters, ``text`` and |
| 40 |
``confidence_threshold``, and returns a list of the detected language codes in |
| 41 |
ISO 639 standards. |
| 42 |
|
| 43 |
|
| 44 |
Wrapper for boilerplate for implementing custom language detections:: |
| 45 |
|
| 46 |
def detect_languages(text, confidence_threshold): |
| 47 |
""" |
| 48 |
Takes 2 parameters, `text` and `confidence_threshold`, and returns |
| 49 |
a list of `languages codes`. |
| 50 |
|
| 51 |
* `text` is the input string whose language needs to be detected. |
| 52 |
|
| 53 |
* `confidence_threshold` is a number between 0 and 1 that indicates the |
| 54 |
minimum confidence required for language matches. |
| 55 |
|
| 56 |
For language detection libraries that, for each language, indicate how |
| 57 |
confident they are that the language matches the input text, you should |
| 58 |
filter out languages with a confidence lower than this value (adjusted, |
| 59 |
if needed, to the confidence range of the target library). |
| 60 |
|
| 61 |
This value comes from the dateparser setting |
| 62 |
`LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD`. |
| 63 |
|
| 64 |
The result must be a list of languages codes (strings). |
| 65 |
""" |
| 66 |
# here you can apply your own logic |
| 67 |
return language_codes |
| 68 |
|