【问题标题】:How to extract number from text in python?如何从python中的文本中提取数字?
【发布时间】:2017-02-17 02:28:28
【问题描述】:

我有下面列出的字符串

str = ['"Consumers_Of_Product": {"count": 13115}']

如何提取数字 13115,因为它会发生变化,以便它始终等于 var。换句话说,我如何从这个字符串中提取这个数字?

我以前做过的大多数事情都没有奏效,我认为这是由于语法造成的。我正在运行 Python 2.7。

【问题讨论】:

    标签: python string python-2.7 integer


    【解决方案1】:

    如果您只想提取该数字,只要该字符串中没有其他数字,您可以使用regex。由于@TigerhawkT3 答案中提到的原因,我将str 重命名为s

    import re
    s = ['"Consumers_Of_Product": {"count": 13115}']
    num = re.findall('\d+', s[0])
    print(num[0])
    13115
    

    【讨论】:

    • 我的答案显示为 ['13115'],我怎样才能让它只是一个数字
    • @Binary111 我编辑了我的答案。正则表达式输出一个列表。我将该列表分配给变量num。您可以打印num[0]获取号码。
    【解决方案2】:

    在该列表中的单个元素上使用ast.literal_eval(你不应该调用str,因为它掩盖了内置,而且它不是字符串),在花括号内(看起来是一个字典元素):

    >>> import ast
    >>> s = ['"Consumers_Of_Product": {"count": 13115}']
    >>> ast.literal_eval('{{{}}}'.format(s[0]))
    {'Consumers_Of_Product': {'count': 13115}}
    

    【讨论】:

    • 由于某种原因,我在提取此整数时仍然出错。
    • @Binary111 - 我不知道你在尝试什么,也不知道它是如何失败的,所以如果没有更多信息,恐怕我无能为力。
    【解决方案3】:

    你有3 options

    但建议使用jsonlib

    import json
    s = ['"Consumers_Of_Product": {"count": 13115}']
    s[0] = '{' + s[0] + '}'
    my_var = json.loads(s[0]) # this is where you translate from string to dict
    print my_var['Consumers_Of_Product']['count']
    # 13115
    

    记住TigerhawkT3 所说的为什么你不应该使用str

    【讨论】:

      【解决方案4】:

      您可以使用regular expression 从字符串中提取您想要的任何内容。这是一个关于HOW TO use Regular expression in python的链接

      此处的示例代码:

      import re
      m = re.search(r'(\d+)', s[0])
      if m:
          print m.group()
      else:
          print 'nothing found'
      

      您的字符串看起来像JSON 字符串,所以如果您正在处理json 字符串,您可以使用json 包来提取字段count 的值

      此处的示例代码(您需要使用 {} 或数组 [] 包装您的字符串):

      import json
      obj = json.loads('{"Consumers_Of_Product": {"count": 13115}}')
      print(obj['Consumers_Of_Product']['count'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-09
        • 2015-11-17
        • 1970-01-01
        • 2020-03-26
        • 1970-01-01
        • 2019-07-09
        相关资源
        最近更新 更多