Expanding English language contractions in Python

后端 未结 9 1550
野性不改
野性不改 2020-12-04 11:19

The English language has a couple of contractions. For instance:

you\'ve -> you have
he\'s -> he is

These can sometimes cause headach

9条回答
  •  悲哀的现实
    2020-12-04 11:53

    You don't need a library, it is possible to do with reg exp for example.

    >>> import re
    >>> contractions_dict = {
    ...     'didn\'t': 'did not',
    ...     'don\'t': 'do not',
    ... }
    >>> contractions_re = re.compile('(%s)' % '|'.join(contractions_dict.keys()))
    >>> def expand_contractions(s, contractions_dict=contractions_dict):
    ...     def replace(match):
    ...         return contractions_dict[match.group(0)]
    ...     return contractions_re.sub(replace, s)
    ...
    >>> expand_contractions('You don\'t need a library')
    'You do not need a library'
    

提交回复
热议问题