Hướng dẫn convert one to 1 python - chuyển đổi một thành 1 con trăn

Đã hỏi 13 năm, 8 tháng trước 13 years, 8 months ago

Đã xem 136k lần 136k times

96

Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.
Learn more.

Tôi cần chuyển đổi

from word2number import w2n

print w2n.word_to_num["two million three thousand nine hundred and eighty four"]
2003984
0 thành
from word2number import w2n

print w2n.word_to_num["two million three thousand nine hundred and eighty four"]
2003984
1,
from word2number import w2n

print w2n.word_to_num["two million three thousand nine hundred and eighty four"]
2003984
2 thành
from word2number import w2n

print w2n.word_to_num["two million three thousand nine hundred and eighty four"]
2003984
3, v.v.

Có cách nào để làm điều này với một thư viện hoặc một lớp học hoặc bất cứ điều gì?

hỏi ngày 29 tháng 1 năm 2009 lúc 20:07Jan 29, 2009 at 20:07

5

Phần lớn mã này là thiết lập NumWords Dict, chỉ được thực hiện trong cuộc gọi đầu tiên.

def text2int[textnum, numwords={}]:
    if not numwords:
      units = [
        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
        "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
        "sixteen", "seventeen", "eighteen", "nineteen",
      ]

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

      scales = ["hundred", "thousand", "million", "billion", "trillion"]

      numwords["and"] = [1, 0]
      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]

    current = result = 0
    for word in textnum.split[]:
        if word not in numwords:
          raise Exception["Illegal word: " + word]

        scale, increment = numwords[word]
        current = current * scale + increment
        if scale > 100:
            result += current
            current = 0

    return result + current

print text2int["seven billion one hundred million thirty one thousand three hundred thirty seven"]
#7100031337

Đã trả lời ngày 29 tháng 1 năm 2009 lúc 22:32Jan 29, 2009 at 22:32

đệ quyrecursive

82K32 Huy hiệu vàng147 Huy hiệu bạc236 Huy hiệu Đồng32 gold badges147 silver badges236 bronze badges

9

Tôi vừa phát hành một mô -đun Python cho pypi có tên Word2Number cho mục đích chính xác. //github.com/akshaynagpal/w2n

Cài đặt nó bằng cách sử dụng:

pip install word2number

Hãy chắc chắn rằng PIP của bạn được cập nhật lên phiên bản mới nhất.

Usage:

from word2number import w2n

print w2n.word_to_num["two million three thousand nine hundred and eighty four"]
2003984

Đã trả lời ngày 2 tháng 1 năm 2016 lúc 18:48Jan 2, 2016 at 18:48

Akshaynagpalakshaynagpalakshaynagpal

2.69731 huy hiệu bạc31 huy hiệu đồng31 silver badges31 bronze badges

5

Tôi cần một cái gì đó hơi khác vì đầu vào của tôi là từ chuyển đổi lời nói sang văn bản và giải pháp không phải lúc nào cũng là tổng hợp các số. Ví dụ: "ZipCode của tôi là một ba ba bốn năm" không nên chuyển đổi thành "mã zip của tôi là 15".

Tôi đã lấy câu trả lời của Andrew và điều chỉnh nó để xử lý một vài trường hợp khác mà mọi người nhấn mạnh là lỗi, và cũng thêm hỗ trợ cho các ví dụ như Zipcode mà tôi đã đề cập ở trên. Một số trường hợp thử nghiệm cơ bản được hiển thị dưới đây, nhưng tôi chắc chắn vẫn còn chỗ để cải thiện.

def is_number[x]:
    if type[x] == str:
        x = x.replace[',', '']
    try:
        float[x]
    except:
        return False
    return True

def text2int [textnum, numwords={}]:
    units = [
        'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
        'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
        'sixteen', 'seventeen', 'eighteen', 'nineteen',
    ]
    tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
    scales = ['hundred', 'thousand', 'million', 'billion', 'trillion']
    ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12}
    ordinal_endings = [['ieth', 'y'], ['th', '']]

    if not numwords:
        numwords['and'] = [1, 0]
        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]

    textnum = textnum.replace['-', ' ']

    current = result = 0
    curstring = ''
    onnumber = False
    lastunit = False
    lastscale = False

    def is_numword[x]:
        if is_number[x]:
            return True
        if word in numwords:
            return True
        return False

    def from_numword[x]:
        if is_number[x]:
            scale = 0
            increment = int[x.replace[',', '']]
            return scale, increment
        return numwords[x]

    for word in textnum.split[]:
        if word in ordinal_words:
            scale, increment = [1, ordinal_words[word]]
            current = current * scale + increment
            if scale > 100:
                result += current
                current = 0
            onnumber = True
            lastunit = False
            lastscale = False
        else:
            for ending, replacement in ordinal_endings:
                if word.endswith[ending]:
                    word = "%s%s" % [word[:-len[ending]], replacement]

            if [not is_numword[word]] or [word == 'and' and not lastscale]:
                if onnumber:
                    # Flush the current number we are building
                    curstring += repr[result + current] + " "
                curstring += word + " "
                result = current = 0
                onnumber = False
                lastunit = False
                lastscale = False
            else:
                scale, increment = from_numword[word]
                onnumber = True

                if lastunit and [word not in scales]:                                                                                                                                                                                                                                         
                    # Assume this is part of a string of individual numbers to                                                                                                                                                                                                                
                    # be flushed, such as a zipcode "one two three four five"                                                                                                                                                                                                                 
                    curstring += repr[result + current]                                                                                                                                                                                                                                       
                    result = current = 0                                                                                                                                                                                                                                                      

                if scale > 1:                                                                                                                                                                                                                                                                 
                    current = max[1, current]                                                                                                                                                                                                                                                 

                current = current * scale + increment                                                                                                                                                                                                                                         
                if scale > 100:                                                                                                                                                                                                                                                               
                    result += current                                                                                                                                                                                                                                                         
                    current = 0                                                                                                                                                                                                                                                               

                lastscale = False                                                                                                                                                                                                              
                lastunit = False                                                                                                                                                
                if word in scales:                                                                                                                                                                                                             
                    lastscale = True                                                                                                                                                                                                         
                elif word in units:                                                                                                                                                                                                             
                    lastunit = True

    if onnumber:
        curstring += repr[result + current]

    return curstring

Một số bài kiểm tra ...

one two three -> 123
three forty five -> 345
three and forty five -> 3 and 45
three hundred and forty five -> 345
three hundred -> 300
twenty five hundred -> 2500
three thousand and six -> 3006
three thousand six -> 3006
nineteenth -> 19
twentieth -> 20
first -> 1
my zip is one two three four five -> my zip is 12345
nineteen ninety six -> 1996
fifty-seventh -> 57
one million -> 1000000
first hundred -> 100
I will buy the first thousand -> I will buy the 1000  # probably should leave ordinal in the string
thousand -> 1000
hundred and six -> 106
1 million -> 1000000

Đã trả lời ngày 20 tháng 11 năm 2018 lúc 20:00Nov 20, 2018 at 20:00

TotalHackTotalHacktotalhack

1.97012 Huy hiệu bạc17 Huy hiệu đồng12 silver badges17 bronze badges

3

Nếu bất cứ ai quan tâm, tôi đã hack một phiên bản duy trì phần còn lại của chuỗi [mặc dù nó có thể có lỗi, chưa kiểm tra nó quá nhiều].

def text2int [textnum, numwords={}]:
    if not numwords:
        units = [
        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
        "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
        "sixteen", "seventeen", "eighteen", "nineteen",
        ]

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

        scales = ["hundred", "thousand", "million", "billion", "trillion"]

        numwords["and"] = [1, 0]
        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]

    ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12}
    ordinal_endings = [['ieth', 'y'], ['th', '']]

    textnum = textnum.replace['-', ' ']

    current = result = 0
    curstring = ""
    onnumber = False
    for word in textnum.split[]:
        if word in ordinal_words:
            scale, increment = [1, ordinal_words[word]]
            current = current * scale + increment
            if scale > 100:
                result += current
                current = 0
            onnumber = True
        else:
            for ending, replacement in ordinal_endings:
                if word.endswith[ending]:
                    word = "%s%s" % [word[:-len[ending]], replacement]

            if word not in numwords:
                if onnumber:
                    curstring += repr[result + current] + " "
                curstring += word + " "
                result = current = 0
                onnumber = False
            else:
                scale, increment = numwords[word]

                current = current * scale + increment
                if scale > 100:
                    result += current
                    current = 0
                onnumber = True

    if onnumber:
        curstring += repr[result + current]

    return curstring

Example:

 >>> text2int["I want fifty five hot dogs for two hundred dollars."]
 I want 55 hot dogs for 200 dollars.

Có thể có vấn đề nếu bạn có, nói, "$ 200". Nhưng, điều này thực sự thô.

Adnan Umer

3.5792 Huy hiệu vàng16 Huy hiệu bạc37 Huy hiệu đồng2 gold badges16 silver badges37 bronze badges

Đã trả lời ngày 4 tháng 8 năm 2016 lúc 7:04Aug 4, 2016 at 7:04

AndrewandrewAndrew

1611 Huy hiệu bạc2 Huy hiệu đồng1 silver badge2 bronze badges

1

Tôi cần xử lý một vài trường hợp phân tích cú pháp bổ sung, chẳng hạn như các từ thứ tự ["thứ nhất", "thứ hai"], các từ được gạch nối ["một trăm"] và các từ thứ tự được gạch nối như ["năm mươi bảy"], vì vậy tôi đã thêm một vài dòng:

def text2int[textnum, numwords={}]:
    if not numwords:
        units = [
        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
        "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
        "sixteen", "seventeen", "eighteen", "nineteen",
        ]

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

        scales = ["hundred", "thousand", "million", "billion", "trillion"]

        numwords["and"] = [1, 0]
        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]

    ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12}
    ordinal_endings = [['ieth', 'y'], ['th', '']]

    textnum = textnum.replace['-', ' ']

    current = result = 0
    for word in textnum.split[]:
        if word in ordinal_words:
            scale, increment = [1, ordinal_words[word]]
        else:
            for ending, replacement in ordinal_endings:
                if word.endswith[ending]:
                    word = "%s%s" % [word[:-len[ending]], replacement]

            if word not in numwords:
                raise Exception["Illegal word: " + word]

            scale, increment = numwords[word]
        
         current = current * scale + increment
         if scale > 100:
            result += current
            current = 0

    return result + current`

Tomerikoo

16.7K15 Huy hiệu vàng38 Huy hiệu bạc54 Huy hiệu đồng15 gold badges38 silver badges54 bronze badges

Đã trả lời ngày 28 tháng 2 năm 2009 lúc 17:10Feb 28, 2009 at 17:10

Jarret Hardiejarret HardieJarret Hardie

92.1k10 Huy hiệu vàng130 Huy hiệu bạc125 Huy hiệu Đồng10 gold badges130 silver badges125 bronze badges

2

Đây là cách tiếp cận trường hợp tầm thường:

>>> number = {'one':1,
...           'two':2,
...           'three':3,}
>>> 
>>> number['two']
2

Hay bạn đang tìm kiếm thứ gì đó có thể xử lý "mười hai nghìn, một trăm bảy mươi hai"?

Đã trả lời ngày 29 tháng 1 năm 2009 lúc 20:25Jan 29, 2009 at 20:25

Jeff Bauerjeff BauerJeff Bauer

13.6K9 Huy hiệu vàng50 Huy hiệu bạc72 Huy hiệu đồng9 gold badges50 silver badges72 bronze badges

Sử dụng gói Python: WordTodigits

pip install wordtodigits

Nó có thể tìm thấy các số có ở dạng từ trong một câu và sau đó chuyển đổi chúng sang định dạng số thích hợp. Cũng chăm sóc phần thập phân, nếu có. Việc thể hiện từ của các số có thể là bất cứ nơi nào trong đoạn văn.The word representation of numbers could be anywhere in the passage.

Tomerikoo

16.7K15 Huy hiệu vàng38 Huy hiệu bạc54 Huy hiệu đồng15 gold badges38 silver badges54 bronze badges

Đã trả lời ngày 28 tháng 2 năm 2009 lúc 17:10May 30, 2020 at 9:03

Jarret Hardiejarret Hardie

92.1k10 Huy hiệu vàng130 Huy hiệu bạc125 Huy hiệu Đồng

Đây là cách tiếp cận trường hợp tầm thường:

Hay bạn đang tìm kiếm thứ gì đó có thể xử lý "mười hai nghìn, một trăm bảy mươi hai"?

Đã trả lời ngày 29 tháng 1 năm 2009 lúc 20:25Jan 29, 2009 at 20:28

Jeff Bauerjeff BauerKena

13.6K9 Huy hiệu vàng50 Huy hiệu bạc72 Huy hiệu đồng5 gold badges35 silver badges46 bronze badges

pip install word2number
1

Sử dụng gói Python: WordTodigits

Tomerikoo

16.7K15 Huy hiệu vàng38 Huy hiệu bạc54 Huy hiệu đồng15 gold badges38 silver badges54 bronze badges

Đã trả lời ngày 28 tháng 2 năm 2009 lúc 17:10Apr 25, 2021 at 23:13

1

Jarret Hardiejarret Hardie

pip install word2number
2

92.1k10 Huy hiệu vàng130 Huy hiệu bạc125 Huy hiệu Đồng

Đây là cách tiếp cận trường hợp tầm thường:4 gold badges43 silver badges67 bronze badges

Hay bạn đang tìm kiếm thứ gì đó có thể xử lý "mười hai nghìn, một trăm bảy mươi hai"?Apr 21, 2010 at 18:37

Đã trả lời ngày 29 tháng 1 năm 2009 lúc 20:25Dawa

Jeff Bauerjeff Bauer2 bronze badges

2

13.6K9 Huy hiệu vàng50 Huy hiệu bạc72 Huy hiệu đồng

pip install word2number
3

Sử dụng gói Python: WordTodigits

from word2number import w2n

print w2n.word_to_num["two million three thousand nine hundred and eighty four"]
2003984
4

Nó có thể tìm thấy các số có ở dạng từ trong một câu và sau đó chuyển đổi chúng sang định dạng số thích hợp. Cũng chăm sóc phần thập phân, nếu có. Việc thể hiện từ của các số có thể là bất cứ nơi nào trong đoạn văn.Mar 5, 2015 at 20:27

Đã trả lời ngày 30 tháng 5 năm 2020 lúc 9:03dimid

Điều này có thể dễ dàng được mã hóa thành một từ điển nếu có một số lượng hạn chế mà bạn muốn phân tích.1 gold badge41 silver badges78 bronze badges

7

Đối với các trường hợp phức tạp hơn một chút, có lẽ bạn sẽ muốn tự động tạo từ điển này, dựa trên ngữ pháp số tương đối đơn giản. Một cái gì đó dọc theo dòng này [tất nhiên, tổng quát ...]

pip install word2number
0

pip install word2number
4

Nếu bạn cần một cái gì đó rộng hơn, thì có vẻ như bạn sẽ cần các công cụ xử lý ngôn ngữ tự nhiên. Bài viết này có thể là một điểm khởi đầu tốt.

Đã trả lời ngày 10 tháng 2 năm 2014 lúc 4:27Feb 10, 2014 at 4:27

Alukachalukachalukach

5.1423 Huy hiệu vàng37 Huy hiệu bạc38 Huy hiệu đồng3 gold badges37 silver badges38 bronze badges

Tôi đã lấy logic của @Recursive và chuyển đổi thành Ruby. Tôi cũng đã mã hóa bàn tra cứu để nó không tuyệt nhưng có thể giúp một người mới hiểu những gì đang xảy ra.

pip install word2number
5

Tôi đang tìm cách xử lý các chuỗi như

from word2number import w2n

print w2n.word_to_num["two million three thousand nine hundred and eighty four"]
2003984
9

Đã trả lời ngày 22 tháng 7 năm 2020 lúc 10:51Jul 22, 2020 at 10:51

Điều này xử lý số trong các từ theo phong cách Ấn Độ, một số phân số, kết hợp các số và từ và cả bổ sung.

pip install word2number
6

TEST:

pip install word2number
7

Đã trả lời ngày 27 tháng 6 năm 2021 lúc 16:56Jun 27, 2021 at 16:56

1

Mã này hoạt động cho một chuỗi dữ liệu:

pip install word2number
8

Đã trả lời ngày 3 tháng 8 năm 2020 lúc 12:51Aug 3, 2020 at 12:51

1

Mã này chỉ hoạt động cho các số dưới 99. Cả Word to Int và Int to Word [để nghỉ ngơi cần thực hiện 10-20 dòng mã và logic đơn giản. Đây chỉ là mã đơn giản cho người mới bắt đầu]:

pip install word2number
9

Tomerikoo

16.7K15 Huy hiệu vàng38 Huy hiệu bạc54 Huy hiệu đồng15 gold badges38 silver badges54 bronze badges

Đã trả lời ngày 21 tháng 8 năm 2017 lúc 12:09Aug 21, 2017 at 12:09

2

Làm thế nào bạn có thể chuyển đổi chuỗi 1 thành số nguyên 1 trong Python?

Trong Python, một chuỗi có thể được chuyển đổi thành một số nguyên bằng hàm int [] tích hợp. Hàm int [] có trong bất kỳ loại dữ liệu python nào và chuyển đổi nó thành một số nguyên.using the built-in int[] function. The int[] function takes in any python data type and converts it into a integer.

Làm thế nào để bạn chuyển đổi các từ thành các số trong Python?

Phương pháp số 1: Sử dụng loop + tham gia [] + split [] Một trong những cách để giải quyết vấn đề này là sử dụng bản đồ, trong đó người ta có thể ánh xạ số bằng các từ và sau đó chia các chuỗi và tham gia lại bằng ánh xạ thành số.Using loop + join[] + split[] One of the ways to solve this problem is to use a map, where one can map the numeric with words and then split the strings and rejoin using mapping to numbers.

Làm thế nào để bạn chuyển đổi một int thành một đôi trong python?

Bạn cần chuyển một trong các thuật ngữ cho giá trị điểm nổi.Rõ ràng bằng cách sử dụng phao [đó là tỷ lệ = float [a]/b hoặc tỷ lệ = a/float [b]] hoặc ngầm bằng cách thêm 0,0: tỷ lệ = [a+0,0]/b.Nếu sử dụng Python 2, bạn có thể từ __future__ nhập bộ phân chia để làm cho bộ phận không phải là một phân chia mà là bản nổi.cast one of the terms to a floating point value. Either explicitly by using float [that is ratio = float[a]/b or ratio=a/float[b] ] or implicitly by adding 0.0 : ratio = [a+0.0]/b . If using Python 2 you can from __future__ import division to make division not be the integral one but the float one.

Làm thế nào để bạn thay đổi loại trong Python?

Để chuyển đổi giữa các loại, bạn chỉ cần sử dụng tên loại làm hàm.Có một số chức năng tích hợp để thực hiện chuyển đổi từ loại dữ liệu này sang loại dữ liệu khác.Các chức năng này trả về một đối tượng mới đại diện cho giá trị được chuyển đổi.use the type name as a function. There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.

Bài Viết Liên Quan

Chủ Đề