【问题标题】:How can I extract numbers based on context of the sentence in python?如何根据python中句子的上下文提取数字?
【发布时间】:2021-03-05 01:48:05
【问题描述】:

我尝试使用正则表达式,但在任何上下文中都没有这样做

例子:: “出售 250 公斤橙子” “我想以每公斤 100 的价格出售 100 公斤的洋葱”

【问题讨论】:

    标签: python nlp data-science extract data-analysis


    【解决方案1】:

    你可以做这样的事情。 首先,您将文本拆分为单词,然后尝试将每个单词转换为数字。 如果单词可以转换为数字,它就是一个数字,如果你确定一个数量后面总是跟着单词“kg”,一旦你找到这个数字,你就可以测试下一个单词是否是“kg”。 然后,根据结果,将值添加到相应的数组中。 在这种特殊情况下,您必须确保单独写入数字(例如“100 kg”而不是“100kg”),否则不会转换。

    string = "250 kg Oranges for Sale. I want to sell 100 kg of Onions at 100 per kg."
    
    # Split the text
    words_list = string.split(" ")
    print(words_list)
    
    # Find which words are numbers
    quantity_array = []
    price_array = []
    for i in range(len(words_list)):
        try:
            number = int(words_list[i])
            # Is it a price or a quantity?
            if words_list[i + 1] == 'kg':
                quantity_array.append(number)
            else:
                price_array.append(number)
        except ValueError:
            print("\'%s\' is not a number" % words_list[i])
    
    # Get the results
    print(quantity_array)
    print(price_array)
    

    【讨论】:

    • 感谢您的回复,我如何区分公斤和价格之前的数字,因为我希望文本格式不同
    • 我已经更新了答案来解决这个问题。
    猜你喜欢
    • 2021-07-07
    • 2014-04-21
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2020-11-13
    相关资源
    最近更新 更多