当前位置: 首页>>代码示例>>Python>>正文


Python num2words.num2words方法代码示例

本文整理汇总了Python中num2words.num2words方法的典型用法代码示例。如果您正苦于以下问题:Python num2words.num2words方法的具体用法?Python num2words.num2words怎么用?Python num2words.num2words使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在num2words的用法示例。


在下文中一共展示了num2words.num2words方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: word_to_num

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def word_to_num(word):
    """ Replace numbers with their written representation. """
    result = word

    match = float_pattern.search(result)

    while match is not None:
        num_word = num2words.num2words(float(match.group().replace(',', '.')), lang='de').lower()
        before = result[:match.start()]
        after = result[match.end():]
        result = ' '.join([before, num_word, after])
        match = float_pattern.search(result)

    match = int_pattern.search(result)

    while match is not None:
        num_word = num2words.num2words(int(match.group()), lang='de')
        before = result[:match.start()]
        after = result[match.end():]
        result = ' '.join([before, num_word, after])
        match = int_pattern.search(result)

    return result 
开发者ID:AASHISHAG,项目名称:deepspeech-german,代码行数:25,代码来源:text_cleaning.py

示例2: modify_xml

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def modify_xml(xml_name, num):
    if num is not None:
        if num <= 5:
            xml_name = xml_name.replace('.xml', num2words.num2words(num) + '.xml')
            # xml_name = 'mass/' + xml_name
            xml_name = 'strength/' + xml_name
        elif num <= 10:
            num -= 5
            xml_name = xml_name.replace('.xml', num2words.num2words(num) + '.xml')
            xml_name = 'strength/' + xml_name
        elif num <= 15:
            num -= 10
            xml_name = xml_name.replace('.xml', num2words.num2words(num) + '.xml')
            xml_name = 'length/' + xml_name
        else:
            raise NotImplementedError
        # print xml_name
    return xml_name 
开发者ID:WilsonWangTHU,项目名称:neural_graph_evolution,代码行数:20,代码来源:walkers.py

示例3: normalize_name

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def normalize_name(name):
    name = re_ordinal_number.sub(lambda m: num2words(int(m.group(1)), to='ordinal'), name)
    return re_strip_non_chars.sub('', name.lower()) 
开发者ID:EdwardBetts,项目名称:osm-wikidata,代码行数:5,代码来源:match.py

示例4: get_syllable_count_word

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def get_syllable_count_word(self, word):
        """
        Formats and retrieves syllable count for individual words, including
        numerals.

        Words are first checked for in `self.counter`. If not found, SbA is
        performed, and if no syllabification exists, then the naive algorithm is
        performed. The resulting syllable count is then added to `self.counter`.

        :param word: Word to count syllables.
        :type word: str | float
        :return n_syllables: Number of syllables.
        :rtype: int
        """

        # Check if word is numerical
        try:
            word = num2words(float(word)).replace('-', ' ')
            return sum([self.get_syllable_count_word(word) for word in word.split()])
        except ValueError:
            # Else, format word
            word = self.regex.sub('', word).lower()

        # Check if word has already been processed
        if word in self.counter:
            return self.counter[word]

        # Remove apostrophes, do SbA
        n_syllables = self._sba(word.replace("'", ''))

        # If SbA fails, do naive
        if n_syllables is None:
            n_syllables = self._naive(word)

        # Add word to already processed words
        self.counter[word] = n_syllables

        return n_syllables 
开发者ID:SwagLyrics,项目名称:autosynch,代码行数:40,代码来源:syllable_counter.py

示例5: alphabetic_value

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def alphabetic_value(number_entity, language):
    from num2words import num2words

    value = number_entity[RESOLVED_VALUE][VALUE]
    if value != int(value):  # num2words does not handle floats correctly
        return None
    return num2words(int(value), lang=language) 
开发者ID:snipsco,项目名称:snips-nlu,代码行数:9,代码来源:string_variations.py

示例6: get_number_as_words

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def get_number_as_words(number, format=constants.words.Ordinal):
    """Return a textual version of the provided word."""
    return num2words(number, to=format) 
开发者ID:GatorEducator,项目名称:gatorgrader,代码行数:5,代码来源:util.py

示例7: transcribe_digits_fun

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def transcribe_digits_fun(self,words):

    from num2words import num2words
    def is_number(s):
      try:
        int(s)
        return 'int'
      except ValueError:
        pass
      try:
        float(s)
        return 'float'
      except ValueError:
        return False

    words = words.split()
    new_words = []
    mutliple_word_number_found = False
    for word in words:
      if is_number(word):
        transcr = num2words(int(word)).upper().replace(',', '').replace('-', ' ').split()
        if len(transcr)>1:
          mutliple_word_number_found = True
        new_words += transcr
      else:
        new_words.append(word)

    new_words = ' '.join(new_words)

    if not new_words == words:
      print (words + ' ---> ' + new_words)

    return new_words 
开发者ID:afourast,项目名称:deep_lip_reading,代码行数:35,代码来源:label_vectorization.py

示例8: digits2words

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def digits2words(phrase, lang='en'):
  wordified = ''
  for word in phrase.split():
    if word.isnumeric():
      word = num2words(float(word), lang=lang)
    wordified = wordified + word + " "
  return wordified[:-1]


# Replace word-form numbers with digits. 
开发者ID:m0ngr31,项目名称:kodi-voice,代码行数:12,代码来源:kodi.py

示例9: save_xml_files

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def save_xml_files(model_names, xml_number, xml_contents):
    # get the xml path ready
    number_str = num2words.num2words(xml_number)
    xml_names = model_names + number_str[0].upper() + number_str[1:] + '.xml'
    xml_file_path = os.path.join(OUTPUT_BASE_DIR, xml_names)

    # save the xml file
    f = open(xml_file_path, 'w')
    f.write(xml_contents)
    f.close() 
开发者ID:WilsonWangTHU,项目名称:neural_graph_evolution,代码行数:12,代码来源:asset_generator.py

示例10: get_env_num_str

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def get_env_num_str(self, number):
        num_str = num2words.num2words(number)
        return num_str[0].upper() + num_str[1:] 
开发者ID:WilsonWangTHU,项目名称:neural_graph_evolution,代码行数:5,代码来源:centipede_env.py

示例11: n2w_1k

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def n2w_1k(x, use_ordinal=False):
    if x > 1000:
        return ''
    return num2words(x, to='ordinal' if use_ordinal else 'cardinal') 
开发者ID:rowanz,项目名称:swagaf,代码行数:6,代码来源:events.py

示例12: _n2w

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def _n2w(n, to):
    try:
        return num2words(n, lang=to_locale(get_language()), to=to)
    except NotImplementedError:
        # fall back to gettext for these words
        gettext_noop("first")
        gettext_noop("second")
        gettext_noop("third")
        gettext_noop("fourth")
        gettext_noop("fifth")
        return _(num2words(n, lang="en", to=to))

# ------------------------------------------------------------------------------ 
开发者ID:linuxsoftware,项目名称:ls.joyous,代码行数:15,代码来源:manythings.py

示例13: toDaysOffsetStr

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def toDaysOffsetStr(offset):
    retval = ""
    if offset <= -2:
        n = num2words(-offset, lang=to_locale(get_language()), to="cardinal")
        retval = _("{N} days before").format(N=n.capitalize())
    elif offset == -1:
        retval = _("The day before")
    elif offset == 1:
        retval = _("The day after")
    elif offset >= 2:
        n = num2words(offset, lang=to_locale(get_language()), to="cardinal")
        retval = _("{N} days after").format(N=n.capitalize())
    return retval

# ------------------------------------------------------------------------------ 
开发者ID:linuxsoftware,项目名称:ls.joyous,代码行数:17,代码来源:manythings.py

示例14: extract_fuzzy_fit

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def extract_fuzzy_fit(mention_x: MentionDataLight, mention_y: MentionDataLight) -> RelationType:
        """
        Check if input mentions has fuzzy fit relation

        Args:
            mention_x: MentionDataLight
            mention_y: MentionDataLight

        Returns:
            RelationType.FUZZY_FIT or RelationType.NO_RELATION_FOUND
        """
        try:
            from num2words import num2words
        except (AttributeError, ImportError):
            logger.error(
                "num2words is not installed, please install nlp_architect with [all] package. "
                + "for example: pip install nlp_architect[all]"
            )
            sys.exit()

        relation = RelationType.NO_RELATION_FOUND
        mention1_str = mention_x.tokens_str
        mention2_str = mention_y.tokens_str
        if difflib.SequenceMatcher(None, mention1_str, mention2_str).ratio() * 100 >= 90:
            relation = RelationType.FUZZY_FIT
            return relation

        # Convert numbers to words
        x_words = [
            num2words(int(w)).replace("-", " ") if w.isdigit() else w for w in mention1_str.split()
        ]
        y_words = [
            num2words(int(w)).replace("-", " ") if w.isdigit() else w for w in mention2_str.split()
        ]

        fuzzy_result = (
            difflib.SequenceMatcher(None, " ".join(x_words), " ".join(y_words)).ratio() * 100 >= 85
        )
        if fuzzy_result:
            relation = RelationType.FUZZY_FIT
        return relation 
开发者ID:NervanaSystems,项目名称:nlp-architect,代码行数:43,代码来源:computed_relation_extraction.py

示例15: number_to_words

# 需要导入模块: import num2words [as 别名]
# 或者: from num2words import num2words [as 别名]
def number_to_words(n, locale="en", num_type="cardinal"):
    """
    Convert an integer numeric value into natural language text.

    :param n: Number to convert.
    :type n: int

    :param locale:
        Language to convert to. Currently supported values:
         - "de"
         - "en"
         - "en_gb"
         - "es"
         - "fr"
         - "lt"
    :type locale: str

    :param num_type:
        Type of number. Must be one of the following values:
         - "cardinal"
         - "ordinal"

    :returns: Natural language text.
    :rtype: str

    :raises: TypeError, ValueError
    """
    if not isinstance(n, int):
        raise TypeError("Expected int, got '%s' instead" % type(n))
    if not isinstance(locale, basestring):
        raise TypeError("Expected basestring, got '%s' instead" % type(locale))
    if not isinstance(num_type, basestring):
        raise TypeError("Expected basestring, got '%s' instead" % type(num_type))
    if num_type == "ordinal" and n < 0:
        raise ValueError("Can't get ordinal value from negative number")

    if num_type == "ordinal":
        try:
            return num2words(n, ordinal=True, lang=locale.lower())
        except NotImplementedError:
            raise ValueError("Language or num_type are not valid.")
    elif num_type == "cardinal":
        try:
            return num2words(n, ordinal=False, lang=locale.lower())
        except NotImplementedError:
            raise ValueError("Language or num_type are not valid.")
    else:
        return num2words(n, ordinal=False, lang="en") 
开发者ID:blackye,项目名称:luscan-devel,代码行数:50,代码来源:natural_language.py


注:本文中的num2words.num2words方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。