Существует ли способ преобразовать слова числа в Целые числа?

У объекта курсора нет метода .where. Вам нужно использовать аргумент фильтра. См. .find документацию.

Сначала необходимо выбрать документ с помощью параметра фильтра, а затем спроецировать поля.

db['WDIData'].find(
    {'Indicator Name': ind},
    {
        'Country Name': 1, 
        'Country Code': 1, 
        'Indicator Name': 1, 
        'Indicator Code': 1, 
        'year': 1
    }
)

61
задан Jonathan Leffler 25 March 2016 в 05:10
поделиться

6 ответов

Большинство этого кода должно настроить numwords dict, который только сделан на первом вызове.

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
102
ответ дан recursive 24 November 2019 в 17:06
поделиться

Вот тривиальный подход случая:

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

Или Вы ищете что-то, что может обработать "двенадцать тысячи, сто семьдесят два" ?

3
ответ дан Jeff Bauer 24 November 2019 в 17:06
поделиться

Спасибо за фрагмент кода... сохранил меня много времени!

я должен был обработать пару дополнительных случаев парсинга, таких как порядковые слова ("первый", "второй"), написанные через дефис слова ("сто"), и написал через дефис порядковые слова как ("пятьдесят седьмой"), таким образом, я добавил пару строк:

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`
9
ответ дан Jarret Hardie 24 November 2019 в 17:06
поделиться

Это могло быть легко быть hardcoded в словарь, если бы существует ограниченная сумма чисел, которые требуется проанализировать.

Для немного более сложных случаев, Вы, вероятно, захотите генерировать этот словарь автоматически, на основе относительно простой грамматики чисел. Что-то вроде этого (конечно, обобщенный...)

for i in range(10):
   myDict[30 + i] = "thirty-" + singleDigitsDict[i]

при необходимости в чем-то более обширном, затем похоже на необходимость в инструментах для обработки естественного языка. Эта статья могла бы быть хорошей начальной точкой.

3
ответ дан Kena 24 November 2019 в 17:06
поделиться

Я использовал импорт nltk nltk.download ('punkt'), и он работает.

from nltk.tokenize import word_tokenize
import nltk
nltk.download('punkt')
macbeth_text_words = (word_tokenize(macbeth_text))
n_words = len(macbeth_text_words)
unique_words = len(set(macbeth_text_words))


print('Total Words: %d' % n_words)
print('Unique Words: %d' % unique_words)
0
ответ дан 24 November 2019 в 17:06
поделиться

Внесены изменения, чтобы text2int (scale) возвращал правильное преобразование. Например, text2int ("сто") => 100.

import re

numwords = {}


def text2int(textnum):

    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", 
                'quadrillion', 'quintillion', 'sexillion', 'septillion', 
                'octillion', 'nonillion', 'decillion' ]

        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', '')]
    current = result = 0
    tokens = re.split(r"[\s-]+", textnum)
    for word in tokens:
        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]

        if scale > 1:
            current = max(1, current)

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

    return result + current
1
ответ дан 24 November 2019 в 17:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: