Convert words to numbers python

How to convert any word into an integer in Python [closed]

Is there a possible way to convert any word, which is obviously in form of a string to an integer in python. That might seem utterly stupid and impossible at first, but if you take a look at it, it’s a good problem to work on that I have been struggling with so long. And yes, I have tried many other ways such as using a list to store different integers to their corresponding letters, however; it didn’t go very well.

def convertWordToInteger(word): return 4 — converts any word (or any other object, for that matter) to an integer. If you have further requirements (such as reversibility of the transformation), you need to specify them.

2 Answers 2

You could create a mapping between primes (2,3,5,7. ) to all characters in your alphabet (a,b,c,d,e. ). Then you map the position of the character inside your word to the next bigger primes.

Then you multiply your character value with your positional value and sum all up:

alphabet = position = [11,13,17,19,23,29,31] text = "aabb12a" def encode(t): """Throws error when not map-able""" return sum(alphabet[x] * position[pos] for pos,x in enumerate(t)) for i in alphabet: print(i,"=>",encode(i)) print(encode(text)) 
('a', '=>', 22) ('1', '=>', 55) ('2', '=>', 77) ('b', '=>', 33) 536 

To reverse the number, you would have to do a prime factorisation, order the resuling summands by theire bigger number ascending, then reverse the mapping of your alphabet.

Читайте также:  Event listeners in php

In this case you would get :

536 = 2*11 + 2*13 + 3*17 + 3*19 + 5*23+ 7*29 + 2*31 

and you can lookup position and character to reconstruct your word.

Give, with 128 characters (ascii) and words up to 50 characters you would get big numbers.

Источник

How to Convert Numeric Words into Numbers using Python

Using Python, we want to convert words into numbers. In this challenge, we will explore how to convert a string into an integer.

The strings simply represent the numbers in words. Let’s convert these words into numbers.

Examples:#

  • “one” => 1
  • “twenty” => 20
  • “two hundred forty-six” => 246
  • “seven hundred eighty-three thousand nine hundred and nineteen” => 783919

Additional Notes:#

  • The minimum number is “zero” (inclusively)
  • The maximum number, which must be supported is 1 million (inclusively)
  • The “and” in e.g. “one hundred and twenty-four” is optional, in some cases it’s present and in others, it’s not
  • All tested numbers are valid, you don’t need to validate them

Test cases to convert words into numbers#

Test.assert_equals(parse_int('one'), 1) Test.assert_equals(parse_int('twenty'), 20) Test.assert_equals(parse_int('two hundred forty-six'), 246) 

The solution in Python to convert words into numbers#

def parse_int(textnum, numwords=<>): # create our default word-lists if not numwords: # singles units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] # tens tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] # larger scales scales = ["hundred", "thousand", "million", "billion", "trillion"] # divisors numwords["and"] = (1, 0) # perform our loops and start the swap for idx, word in enumerate(units): numwords[word] = (1, idx) for idx, word in enumerate(tens): numwords[word] = (1, idx * 10) for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0) # primary loop current = result = 0 # loop while splitting to break into individual words for word in textnum.replace("-"," ").split(): # if problem then fail-safe if word not in numwords: raise Exception("Illegal word: " + word) # use the index by the multiplier scale, increment = numwords[word] current = current * scale + increment # if larger than 100 then push for a round 2 if scale > 100: result += current current = 0 # return the result plus the current return result + current 
  1. Solve The Triangle of Odd Numbers using Python
  2. “Who likes it” code Challenge in Python
  3. Python 4 New Features Planned
  4. Custom RGB To Hex Conversion with Python
  5. How to write a Chain Adding Function in Python
  6. Get the next biggest number with the same digits using Python
  7. Solving Tribonacci Sequence with Python
  8. The Casino Chips Problem Solved with Python
  9. Check if Isogram using Python
  10. Find the Longest Common Prefix using Python

Источник

How would I convert words to numbers in python 3 (own keys and values)? [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

I am writing a Python 3 script that will take words in a text file and convert them into numbers (my own, not ASCII, so no ord function). I have assigned each letter to an integer and would like each word to be the sum of its letters’ numerical value. The goal is to group each word with the same numerical value into a dictionary. I am having great trouble recombining the split words as numbers and adding them together. I am completely stuck with this script (it is not complete yet. **Btw, I know the easier way of creating the l_n dictionary below, but since I’ve already written it out, I am a little lazy to change it for now, but will do so after the completion of the script.

l_n = < "A": 1, "a": 1, "B": 2, "b": 2, "C": 3, "c": 3, "D": 4, "d": 4, "E": 5, "e": 5, "F": 6, "f": 6, "G": 7, "g": 7, "H": 8, "h": 8, "I": 9, "i": 9, "J": 10, "j": 10, "K": 11, "k": 11, "L": 12, "l": 12, "M": 13, "m": 13, "N": 14, "n": 14, "O": 15, "o": 15, "P": 16, "p": 16, "Q": 17, "q": 17, "R": 18, "r": 18, "S": 19, "s": 19, "T": 20, "t": 20, "U": 21, "u": 21, "V": 22, "v": 22, "W": 23, "w": 23, "X": 24, "x": 24, "Y": 25, "y": 25, "Z": 26, "z": 26, >words_list = [] def read_words(file): opened_file = open(file, "r") contents = opened_file.readlines() for i in range(len(contents)): words_list.extend(contents[i].split()) opened_file.close() return words_list read_words("file1.txt") new_words_list = list(set(words_list)) numbers_list = [] w_n = <> def words_to_numbers(new_words_list, l_n): local_list = new_words_list[:] local_number_list = [] for word in local_list: local_number_list.append(word.split()) for key in l_n: local_number_list = local_number_list.replace( **#I am stuck on the logic in this section.** words_to_numbers(new_words_list, l_n) print(local_list) 

I’ve tried looking for an answer on stackoverflow but was unable to find an answer. Thank you for your help.

Источник

Welcome to word2number’s documentation!¶

This is a Python module to convert number words (eg. twenty one) to numeric digits (21). It works for positive numbers upto the range of 999,999,999,999 (i.e. billions).

Installation¶

Please ensure that you have updated pip to the latest version before installing word2number.

You can install the module using Python Package Index using the below command.

Make sure you install all requirements given in requirements.txt

pip install -r requirements.txt 

Usage¶

First you have to import the module using the below code.

from word2number import w2n 

Then you can use the word_to_num method to convert a number-word to numeric digits, as shown below.

>>> print w2n.word_to_num("two million three thousand nine hundred and eighty four") 2003984 >>> print(w2n.word_to_num('two point three')) 2.3 >>> print(w2n.word_to_num('112')) 112 >>> print(w2n.word_to_num('point one')) 0.1 >>> print(w2n.word_to_num('one hundred thirty-five')) 135 >>> print(w2n.word_to_num('million million')) Error: Redundant number! Please enter a valid number word (eg. two million twenty three thousand and forty nine) None >>> print(w2n.word_to_num('blah')) Error: No valid number words found! Please enter a valid number word (eg. two million twenty three thousand and forty nine) None 

Bugs/Errors¶

Please ensure that you have updated pip to the latest version before installing word2number.

If you find any bugs/errors in the usage of above code, please raise an issue through Github. If you don’t know how to use Github or raise an issue through it, I suggest that you should learn it. Else, send an email to akshay2626 @ gmail . com with a clear example that can reproduce the issue.

Contributors¶

Источник

word2number 1.1

Convert number words eg. three hundred and forty two to numbers (342).

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License (The MIT License (MIT) )

Метки numbers, convert, words

Сопровождающие

Классификаторы

  • Development Status
    • 5 — Production/Stable
    • Customer Service
    • Developers
    • Education
    • Healthcare Industry
    • Information Technology
    • OSI Approved :: MIT License
    • English
    • OS Independent
    • Python
    • Python :: 2
    • Python :: 2.7
    • Python :: 3.6
    • Documentation :: Sphinx
    • Education
    • Education :: Computer Aided Instruction (CAI)
    • Education :: Testing
    • Games/Entertainment :: Board Games
    • Games/Entertainment :: Turn Based Strategy
    • Scientific/Engineering :: Human Machine Interfaces
    • Software Development :: Libraries :: Python Modules
    • Software Development :: Version Control :: Git
    • Utilities

    Описание проекта

    Word to Number

    This is a Python module to convert number words (eg. twenty one) to numeric digits (21). It works for positive numbers upto the range of 999,999,999,999 (i.e. billions).

    Installation

    Please ensure that you have updated pip to the latest version before installing word2number.

    You can install the module using Python Package Index using the below command.

    Make sure you install all requirements given in requirements.txt

    Usage

    First you have to import the module using the below code. .. code-block:: python

    Then you can use the word_to_num method to convert a number-word to numeric digits, as shown below.

    Bugs/Errors

    Please ensure that you have updated pip to the latest version before installing word2number.

    If you find any bugs/errors in the usage of above code, please raise an issue through Github. If you don’t know how to use Github or raise an issue through it, I suggest that you should learn it. Else, send an email to akshay2626 @ gmail . com with a clear example that can reproduce the issue.

    Contributors

    Источник

Оцените статью