簡體   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