Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python查找文本中的x位数字_Python_Search_Text Processing - Fatal编程技术网

使用Python查找文本中的x位数字

使用Python查找文本中的x位数字,python,search,text-processing,Python,Search,Text Processing,有没有更好更有效的方法来查找文本中由x位组成的x位数字 我的方式: 编辑: 编辑2: for n in range(0,len(text)): try: int(text[n:n+x]) result = text[n:n+x] except: pass return result 您可以使用regex来实现这一点。比如说 >>> import re >>> s = "abc 123 4567

有没有更好更有效的方法来查找文本中由x位组成的x位数字

我的方式:

编辑:

编辑2:

for n in range(0,len(text)):
    try:  
       int(text[n:n+x])
       result = text[n:n+x]
    except:
       pass

return result

您可以使用regex来实现这一点。比如说

>>> import re

>>> s = "abc 123 45678"
>>> re.search("(\d{5})\D",s).group()
'45678'
查找s中的5位数字。或者如果您有多个号码,请使用findall

>>> s = "abc 123 45678\nbla foo 65432"
>>> re.findall("(\d{5})\D",s)
['45678', '65432']

您可以使用regex来实现这一点。比如说

>>> import re

>>> s = "abc 123 45678"
>>> re.search("(\d{5})\D",s).group()
'45678'
查找s中的5位数字。或者如果您有多个号码,请使用findall

>>> s = "abc 123 45678\nbla foo 65432"
>>> re.findall("(\d{5})\D",s)
['45678', '65432']
输出

输出


是的,正则表达式!但是你的文字和数字看起来怎么样?@greole我已经编辑了我的示例。我有很多行,每行上都有我想要的5位数字。所以我想知道怎么做。。。我不认为iInstance做了你认为它做的事情。isinstancesomestring[此处的某些片段],int将始终为False。字符串片段仍然是字符串,即使它是由十进制数字组成的。是的regexps!但是你的文字和数字看起来怎么样?@greole我已经编辑了我的示例。我有很多行,每行上都有我想要的5位数字。所以我想知道怎么做。。。我不认为iInstance做了你认为它做的事情。isinstancesomestring[此处的某些片段],int将始终为False。字符串片段仍然是字符串,即使它是由十进制数字组成的。
import re                                             
string = "hello 123 world 5678 897 word"              
number_length = 3                                     
pattern= r"\D(\d{%d})\D" % number_length   # \D to avoid matching 567           
print re.findall(pattern, string)
["123","897"]