Как написать число словами python

Простой python модуль для генерации названия числа.

Позволяет получить из числа, например, 100500 его «название» (генерация текста из числа, преобразование числа в текст), например «сто пятьсот».
Позволяет так же использовать наименование единиц измерения например 100500 (рублей, рубля, рубль) > «сто пятьсот рублей»

Примеры использования

Генерация названия int числа

>>> from number_to_text import num2text
>>> print num2text(100500)
u"сто пятьсот"
>>> print num2text(1234567891)
u'один миллиард двести тридцать четыре миллиона пятьсот шестьдесят семь тысяч восемьсот девяносто один'

Генерация названия int числа с единицами измерения

>>> from number_to_text import num2text
>>> male_units = ((u'рубль', u'рубля', u'рублей'), 'm')
>>> female_units = ((u'копейка', u'копейки', u'копеек'), 'f')
>>> # male_units это plural-формы для единицы измерения и ее род 'm' - мужской, 'f' - женский
>>> num2text(101, male_units)  # первая plural форма, мужской род
u'сто один рубль'
>>> num2text(102, male_units)  # вторая plural форма, мужской род
u'сто два рубля'
>>> num2text(101, female_units)  # первая plural форма, женский род
u'сто одна копейка'
>>> num2text(102, female_units)  # вторая plural форма, женский род
u'сто две копейки'
>>> num2text(105, female_units)  # третья plural форма, женский род
u'сто пять копеек'

Генерация названия дробного числа

>>> from number_to_text import decimal2text
>>> import Decimal
>>> int_units = ((u'рубль', u'рубля', u'рублей'), 'm')
>>> exp_units = ((u'копейка', u'копейки', u'копеек'), 'f')
>>> decimal2text(
        decimal.Decimal('105.245'),
        int_units=int_units,
        exp_units=exp_units)
u'сто пять рублей двадцать четыре копейки'
>>> decimal2text( # можно задать число цифр после запятой (округление)
        decimal.Decimal('102.2450'),
        places=4,
        int_units=int_units,
        exp_units=exp_units)
u'сто два рубля две тысячи четыреста пятьдесят копеек' xD

Еще больше примеров можно найти в юнит-тестах.

TODO

  • Нучиться возвращать не строку а что-то более удобное для дальнейшей обработки.
  • Добваить в PyPi ???
  • Отрефакторить
  • Больше комментариев в коде!

This worked for me in Python 3.x:

print('Type any number here: ')
number = input()
int_side = number
dec_side = ''
for i in range(0, len(number)):
    if number[i] == '.':
        int_side = number[:i]
        dec_side = number[i + 1:]
        break
while not (int_side.isdigit()) or not (dec_side.isdigit()) and dec_side != '':
    dec_side = ''
    print('Only numbers are allowed! (decimals included, but not fractions)')
    print('Type any number here: ')
    number = input()
    int_side = number
    for i in range(0, len(number)):
        if number[i] == '.':
            int_side = number[:i]
            dec_side = number[i + 1:]
    user_choice = input()
int_length = len(int_side)
ones = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ']
teens = ['ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ',
         'nineteen ']
decades = ['', '', 'twenty ', 'thirty ', 'forty ', 'fifty ', 'sixty ', 'seventy ', 'eighty ', 'ninety ']
hundreds = ['', 'one hundred ', 'two hundred ', 'three hundred ', 'four hundred ', 'five hundred ', 'six hundred ',
            'seven hundred ', 'eight hundred ', 'nine hundred ']
comma = ['thousand, ', 'million, ', 'trillion, ', 'quadrillion, ']
word = ''
int_length = len(int_side)
dec_length = len(dec_side)
change = int_length
up_change = 0
while change > 0:
    if int_side == '':
        break
    if number == '0':
        word = 'zero'
        break
    elif change > 1 and int_side[change - 2] == '1':
        for i in range(0, 10):
            if int_side[change - 1] == str(i):
                word = teens[i] + word
    else:
        if change > 0:
            for i in range(0, 10):
                if int_side[change - 1] == str(i):
                    word = ones[i] + word
        if change > 1:
            for i in range(0, 10):
                if int_side[change - 2] == str(i):
                    word = decades[i] + word
    if change > 2:
        for i in range(0, 10):
            if int_side[change - 3] == str(i):
                word = hundreds[i] + word
    if change > 3:
        word = comma[up_change] + word
    change -= 3
    up_change += 1
word += 'point '
for i in range(0, len(dec_side)):
    for x in range(0, 10):
        if dec_side[i] == str(x):
            word += ones[x]
print(word)

This is an example:

Type any number here: 13243214.1324hk
Only numbers are allowed! (decimals included, but not fractions)
Type any number here: 13243214.1324
thirteen million, two hundred forty three thousand, two hundred 
fourteen point one three two four

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    num2words module in Python, which converts number (like 34) to words (like thirty-four). Also, this library has support for multiple languages. In this article, we will see how to convert number to words using num2words module. Installation One can easily install num2words using pip.

    pip install num2words

    Consider the following two excerpts from different files taken from 20 Newsgroups, a popular NLP database. Pre-processing 20 Newsgroups effectively has remained to be a matter of interest.

    In article, Martin Preston writes: Why not use the PD C library for reading/writing TIFF files? It took me a good 20 minutes to start using them in your own app. ISCIS VIII is the eighth of a series of meetings which have brought together computer scientists and engineers from about twenty countries. This year’s conference will be held in the beautiful Mediterranean resort city of Antalya, in a region rich in natural as well as historical sites.

    In the above two excerpts, one can observe that the number ’20’ appears in both numeric and alphabetical forms. Simply following the pre-processing steps, that involve tokenization, lemmatization and so on would not be able to map ’20’ and ‘twenty’ to the same stem, which is of contextual importance. Luckily, we have the in-built library, num2words which solves this problem in a single line. Below is the sample usage of the tool. 

    Python

    from num2words import num2words

    print(num2words(36))

    print(num2words(36, to = 'ordinal'))

    print(num2words(36, to = 'ordinal_num'))

    print(num2words(36, to = 'year'))

    print(num2words(36, to = 'currency'))

    print(num2words(36, lang ='es'))

    Output:

    thirty-six
    thirty-sixth
    36th
    zero euro, thirty-six cents
    treinta y seis

    Time complexity: O(1).
    Auxiliary space: O(1).

    Therefore, in the pre-processing step, one could convert ALL numeric values to words for better accuracy in the further stages. References: https://pypi.org/project/num2words/

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    num2words module in Python, which converts number (like 34) to words (like thirty-four). Also, this library has support for multiple languages. In this article, we will see how to convert number to words using num2words module. Installation One can easily install num2words using pip.

    pip install num2words

    Consider the following two excerpts from different files taken from 20 Newsgroups, a popular NLP database. Pre-processing 20 Newsgroups effectively has remained to be a matter of interest.

    In article, Martin Preston writes: Why not use the PD C library for reading/writing TIFF files? It took me a good 20 minutes to start using them in your own app. ISCIS VIII is the eighth of a series of meetings which have brought together computer scientists and engineers from about twenty countries. This year’s conference will be held in the beautiful Mediterranean resort city of Antalya, in a region rich in natural as well as historical sites.

    In the above two excerpts, one can observe that the number ’20’ appears in both numeric and alphabetical forms. Simply following the pre-processing steps, that involve tokenization, lemmatization and so on would not be able to map ’20’ and ‘twenty’ to the same stem, which is of contextual importance. Luckily, we have the in-built library, num2words which solves this problem in a single line. Below is the sample usage of the tool. 

    Python

    from num2words import num2words

    print(num2words(36))

    print(num2words(36, to = 'ordinal'))

    print(num2words(36, to = 'ordinal_num'))

    print(num2words(36, to = 'year'))

    print(num2words(36, to = 'currency'))

    print(num2words(36, lang ='es'))

    Output:

    thirty-six
    thirty-sixth
    36th
    zero euro, thirty-six cents
    treinta y seis

    Time complexity: O(1).
    Auxiliary space: O(1).

    Therefore, in the pre-processing step, one could convert ALL numeric values to words for better accuracy in the further stages. References: https://pypi.org/project/num2words/

    Project description

    num_to_rus

    codecov
    GitHub Actions
    PyPI version

    Небольшая библиотека, позволяющая переводить числа в слова на русском
    языке

    Установка

    Чтобы установить библиотеку, нужно выполнить следующую команду:

    pip install num_to_rus
    

    Использование

    Для того, чтобы использовать библиотеку, нужно импортировать
    Converter из num_to_rus, создать его экземпляр и вызвать
    у него метод convert, которому передать число, которое нужно конвертировать

    from num_to_rus import Converter
    
    conv = Converter()
    
    print(conv.convert(512)) # 'пятьсот двенадцать'
    

    Тестирование

    Чтобы запустить тесты, нужно выполнить следующую команду:

    python -m unittest
    

    Лицензия

    Проект находится под лицензией GPL-3.0

    Download files

    Download the file for your platform. If you’re not sure which to choose, learn more about installing packages.

    Source Distribution

    Built Distribution

    num2words — библиотека, которая переводит числа (например, 42) в слова (сорок два) или даже в порядковые числительные (сорок второй).

    Очень проста в использовании:

    from num2words import num2words
    
    print(num2words(42))  # Выведет forty-two
    print(num2words(42, to='ordinal')) # Выведет forty-second
    print(num2words(42, lang='fr'))  # Выведет quarante-deux
    

    Помимо основного аргумента-числа есть необязательные, дополнительные аргументы:

    • Аргумент to может принимать следущие значения:

      • "cardinal" — просто перевод в число: 2019 —> two thousand and nineteen.
      • "ordinal" — перевод в порядковое числительное: 2019 —> two thousand and nineteenth.
      • "ordinal_num" — оставить числом: 2019 —> 2019th.
      • "year" — в год: 2019 —> twenty nineteen
      • "currency" — в евро: 2019 —> twenty euro, nineteen cents
    • lang — определяет в какой язык переводить:

      • "en" (English, default)
      • "ar" (Arabic)
      • "cz" (Czech)
      • "de" (German)
      • "dk" (Danish)
      • "en_GB" (English — Great Britain)
      • "en_IN" (English — India)
      • "es" (Spanish)
      • "es_CO" (Spanish — Colombia)
      • "es_VE" (Spanish — Venezuela)
      • "eu" (EURO)
      • "fi" (Finnish)
      • "fr" (French)
      • "fr_CH" (French — Switzerland)
      • "fr_BE" (French — Belgium)
      • "fr_DZ" (French — Algeria)
      • "he" (Hebrew)
      • "id" (Indonesian)
      • "it" (Italian)
      • "ja" (Japanese)
      • "ko" (Korean)
      • "lt" (Lithuanian)
      • "lv" (Latvian)
      • "no" (Norwegian)
      • "pl" (Polish)
      • "pt" (Portuguese)
      • "pt_BR" (Portuguese — Brazilian)
      • "sl" (Slovene)
      • "sr" (Serbian)
      • "ro" (Romanian)
      • "ru" (Russian)
      • "sl" (Slovene)
      • "tr" (Turkish)
      • "th" (Thai)
      • "vi" (Vietnamese)
      • "nl" (Dutch)
      • "uk" (Ukrainian)

    Некоторые коды состоят из языка и страны: fr_FR. Если страна не поддерживается, но поддерживается язык, то программа использует код языка: fr. Если вы используете язык не из этого списка, получите NotImplementedError.


    Попробуйте бесплатные уроки по Python

    Получите крутое код-ревью от практикующих программистов с разбором ошибок и рекомендациями, на что обратить внимание — бесплатно.

    Переходите на страницу учебных модулей «Девмана» и выбирайте тему.

    -30 / 10 / 0

    Регистрация: 29.12.2018

    Сообщений: 214

    1

    Написать число словами

    18.01.2019, 21:23. Показов 48541. Ответов 12


    Напишите функцию number_in_english(number), которая принимает число от 0 до 999, а возвращает строку, в которой это число записано словами на английском языке.
    Пример работы функции:
    number_in_english(3) # => three
    number_in_english(78) # => seventy eight
    number_in_english(115) # => one hundred and fifteen
    number_in_english(729) # => seven hundred and twenty nine
    Пример 1
    Ввод
    print(number_in_english(0).lower())
    Вывод
    zero
    Пример 2
    Ввод
    print(number_in_english(1).lower())
    Вывод
    one

    вот мой код:

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    str1 = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
            'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
            'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', '']
    str2 = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy',
            'eighty', 'ninety']
     
     
    def number_in_english(number):
        if not number:
            return 'zero'
        if number // 100 and number % 100:
            result = '{} hundred and '.format(str1[number // 100 - 1])
        elif number // 100:
            result = '{} hundred'.format(str1[number // 100 - 1])
        else:
            result = ''
        if number % 100 <= 19:
            result += str1[number % 100 - 1]
        else:
            result = result + str2[number % 100 // 10 - 2] + ' ' + str1[number % 10 - 1]
        return result

    как убрать эту ошибку

    Ввод
    print(number_in_english(20).lower())
    Ожидаемый результат
    twenty
    Вывод
    twenty
    ошибка в пробеле в конце, подскажите как ее убрать

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



    0



    Понравилась статья? Поделить с друзьями:
  • Как написать число двадцать пятое
  • Как написать число дату на английском
  • Как написать число грэма
  • Как написать число буквами правильно
  • Как написать число бесконечность