繁体   English   中英

如何在Python中从字符串中提取数字及其索引

[英]How to extract numbers and their indices from a string in Python

我正在尝试编写一个函数,该函数将接收字符串并返回一个字典,其中包含该字符串中包含的所有数字以及它们开始的索引。

例如,字符串"1this is a 134 test15"将产生字典{ 0:1, 11:134, 19:15 } "1this is a 134 test15" { 0:1, 11:134, 19:15 }

我已经看到了许多使用正则表达式的类似问题的解决方案,它们可以很好地提取数字本身,但是我一直无法找到一种方法将这些数字与它们所在的索引相关联。

是否可以使用正则表达式从字符串中提取此类信息,或者有其他方法可以更适合此类应用程序。

In [44]: strs="1this is a 134 test15"

In [45]: {m.start(0):int(m.group(0)) for m in re.finditer("\d+", strs)}
Out[45]: {0: 1, 11: 134, 19: 15}
>>> import re
>>> text = "1this is a 134 test15"
>>> d = dict((m.start(), int(m.group())) for m in re.finditer(r'\d+', text))
>>> d
{0: 1, 19: 15, 11: 134}

正则表达式MatchObjectstart()方法将提供当前匹配项的字符串偏移量。

如果您正在寻找功能,我希望这可能有用。 当然,这是一种更简单的方法。 但是,这就是我已经解决的问题。 我已经尽力了 :)

def function(string,dic={},p=0):

   if len(string)==0:
      return dic

   else:
      i=0
      if string[0] in '1234567890':
        while string[i] in '0123456789':
          i+=1
          p+=1
        dic[p-len(string[:1])]=int(string[:i])
        string=string[i:]
        return function(string,dic,p)
      else: 
        p+=1
        return function(string[1:],dic,p)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM