English 中文(简体)
英文插座序号
原标题:Convert numbers to English strings
The bounty expires in 7 days. Answers to this question are eligible for a +50 reputation bounty. alvas wants to draw more attention to this question.

http://www.easysurf.cc/cnvert18.htm 试图将数字扼杀变成一个english,但它们正在带来自然的稳健产出。

For example, on http://www.easysurf.cc/cnvert18.htm:

[in]: 100456
[out]:  one hundred  thousand four hundred fifty-six

http://www.calculator.org/calculate-online/mathematics/text- number.aspx” rel=“nofollow” http://www.calculator.org/calculate-online/mathematics/text- number.aspx:

[in]: 100456
[out]: one hundred thousand, four hundred and fifty-six

[in]: 10123124001
[out]: ten billion, one hundred and twenty-three million, one hundred and twenty-four thousand, one 

但是,它在某些时候打破了:

[in]: 10000000001
[out]: ten billion, , , one 

I ve撰写了我自己的版本,但涉及许多规则,从:

import codecs

def num2word (num):
  ones = {1:"one",2:"two",3:"three",4:"four",
          5:"five",6:"six",7:"seven",8:"eight",
          9:"nine",0:"zero",10:"ten"}
  teens = {11:"eleven",12:"twelve",13:"thirteen",
           14:"fourteen",15:"fifteen"}
  tens = {2:"twenty",3:"thirty",4:"forty",
          5:"fifty",6:"sixty",7:"seventy",
          8:"eighty",9:"ninety"}
  lens = {3:"hundred",4:"thousand",6:"hundred",7:"million",
          8:"million", 9:"million",10:"billion"#,13:"trillion",11:"googol",
          }

  if num > 999999999:
    return "Number more than 1 billion"

  # Ones
  if num < 11:
    return ones[num]
  # Teens
  if num < 20:
    word = ones[num%10] + "teen" if num > 15 else teens[num]
    return word
  # Tens
  if num > 19 and num < 100:
    word = tens[int(str(num)[0])]
    if str(num)[1] == "0":
      return word
    else:
      word = word + " " + ones[num%10]
      return word

  # First digit for thousands,hundred-thousands.
  if len(str(num)) in lens and len(str(num)) != 3:
    word = ones[int(str(num)[0])] + " " + lens[len(str(num))]
  else:
    word = ""

  # Hundred to Million  
  if num < 1000000:
    # First and Second digit for ten thousands.  
    if len(str(num)) == 5:
      word = num2word(int(str(num)[0:2])) + " thousand"
    # How many hundred-thousand(s).
    if len(str(num)) == 6:
      word = word + " " + num2word(int(str(num)[1:3])) + 
            " " + lens[len(str(num))-2]
    # How many hundred(s)?
    thousand_pt = len(str(num)) - 3
    word = word + " " + ones[int(str(num)[thousand_pt])] + 
            " " + lens[len(str(num))-thousand_pt]
    # Last 2 digits.
    last2 = num2word(int(str(num)[-2:]))
    if last2 != "zero":
      word = word + " and " + last2
    word = word.replace(" zero hundred","")
    return word.strip()

  left, right =   ,    
  # Less than 1 million.
  if num < 100000000:
    left = num2word(int(str(num)[:-6])) + " " + lens[len(str(num))]
    right = num2word(int(str(num)[-6:]))
  # From 1 million to 1 billion.
  if num > 100000000 and num < 1000000000:
    left = num2word(int(str(num)[:3])) +  " " + lens[len(str(num))]
    right = num2word(int(str(num)[-6:]))
  if int(str(num)[-6:]) < 100:
    word = left + " and " + right
  else:  
    word = left + " " + right
  word = word.replace(" zero hundred","").replace(" zero thousand"," thousand")
  return word

print num2word(int(raw_input("Give me a number:
")))

www.un.org/Depts/DGACM/index_spanish.htm 我怎样才能使文字一号书写接受>ill?。

www.un.org/Depts/DGACM/index_spanish.htm 是否还有其他办法获得同样的产出?

www.un.org/Depts/DGACM/index_spanish.htm 我的法典能否用较少的手法书写?

最佳回答

对这一问题采取更为一般性的办法,采用重复的划分(即divmod),并且只使用必要的硬编码。

例如,divmod (1034393, 1000000)-> (1, 34393)<>code>,因此,你有效地发现数百万美元,留待作进一步计算。

Possibly more illustrative example: divmod(1034393, 1000) -> (1034, 393) which allows you to take off groups of 3 decimal digits at a time from the right.

In English we tend to group digits in threes, and similar rules apply. This should be parameterized and not hard coded. For example, "303" could be three hundred and three million, three hundred and three thousand, or three hundred and three. The logic should be the same except for the suffix, depending on what place you re in. Edit: looks like this is sort of there due to recursion.

这里是某种做法的局部例子,我指的是,使用发电机,在基因组中操作,而不是在任何地方做<代码>int(str(i) [.])

say_base = [ zero ,  one ,  two ,  three ,  four ,  five ,  six ,  seven ,
     eight ,  nine ,  ten ,  eleven ,  twelve ,  thirteen ,  fourteen ,
     fifteen ,  sixteen ,  seventeen ,  eighteen ,  nineteen ]

say_tens = [  ,   ,  twenty ,  thirty ,  forty ,  fifty ,  sixty ,  seventy ,
     eighty ,  ninety ]

def hundreds_i(num):
    hundreds, rest = divmod(num, 100)
    if hundreds:
        yield say_base[hundreds]
        yield   hundred 
    if 0 < rest < len(say_base):
        yield   and  
        yield say_base[rest]
    elif rest != 0:
        tens, ones = divmod(rest, 10)
        yield   and  
        yield say_tens[tens]
        if ones > 0:
            yield  - 
            yield say_base[ones]

assert "".join(hundreds_i(245)) == "two hundred and forty-five"
assert "".join(hundreds_i(999)) ==  nine hundred and ninety-nine 
assert "".join(hundreds_i(200)) ==  two hundred 
问题回答

由于目前接受的回答有一些“零”问题,我在此提出另一个答案:

def number_to_text(n, *, hyphen="-", joiner="and", comma=","):
    unitNames = ["one", "two", "three", "four", "five", "six", "seven", "eight", 
                 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
                 "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
    tensNames = ["twenty", "thirty", "forty", "fifty", 
                 "sixty", "seventy", "eighty", "ninety"]
    tripletNames = ["", "thousand"] + [s + "illion" 
                        for s in ["m", "b", "tr", "quadr", "quint", 
                                  "sext", "sept", "oct", "non"]
                    ] + [s + "decillion"
                        for s in ["", "un", "duo", "tre", "quattuor", 
                                  "quin", "sex", "septen", "octo", "novem"]
                    ] + ["vigintillion"]  # add as needed....
                
    def triplets(n):
        for tripletName in tripletNames:
            num = n % 1000
            n //= 1000
            if num == 0:
                continue
            hundreds = num // 100
            num %= 100
            tens =  num // 10 if num > 19 else 0
            num -= tens * 10
            yield ((unitNames[hundreds-1] + " hundred " if hundreds else "")
                + (joiner + " " if joiner and (n or hundreds) and (tens or num) else "") 
                + (tensNames[tens-2] + (hyphen if num else " ") if tens else "")
                + (unitNames[num-1] + " " if num else "")
                + tripletName).strip()
            if n == 0:
                return
        raise ValueError("number too large for this converter")

    return (comma + " ").join(reversed(list(triplets(n)))) if n else "zero"

例举:

print(number_to_text(1234567890123456789, hyphen="-", joiner="and", comma=","))

产出:

1 兆克、2百三十四 qua、5 六十万亿、8亿和90亿、1亿2千3百万、4亿至5千6千、7百和八十九

如果你不喜欢 com子,也不喜欢“和”,那么就通过空洞,来选择相应的选择:

print(number_to_text(101000001, hyphen="-", joiner="", comma=""))

页: 1

NB: The use the shortpad 。 如果需要很长的比额表,则相应地更新名单<代码>tripletNames。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签