Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.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脚本从特定行中只读数字_Python - Fatal编程技术网

如何使用python脚本从特定行中只读数字

如何使用python脚本从特定行中只读数字,python,Python,例如,如何使用python脚本从特定行中只读数字 “1009运行测试作业”在这里,我应该只读数字“1009”,而不是“1009运行测试作业”一个简单的regexp应该执行以下操作: import re match = re.match(r"(\d+)", "1009 run test jobs") if match: number = match.group() 使用正则表达式: >>> import re >>> x = "1009 run tes

例如,如何使用python脚本从特定行中只读数字


“1009运行测试作业”在这里,我应该只读数字“1009”,而不是“1009运行测试作业”

一个简单的regexp应该执行以下操作:

import re
match = re.match(r"(\d+)", "1009 run test jobs")
if match:
    number = match.group()

使用正则表达式:

>>> import re
>>> x = "1009 run test jobs"
>>> re.sub("[^0-9]","",x)
>>> re.sub("\D","",x) #better way

或者,如果您的数字总是排在int(line.split()[0])的第一位,或者简单地检查其数字是否为字符串

[如果s.isdigit(),则str.split()中s的int(s)]

其中str是您的文本字符串。

可以肯定有一种“更具pythonic”的方式,但这对我来说很有效:

s='teststri3k2k3s21k'
outs=''
for i in s:
    try:
        numbr = int(i)
        outs+=i
    except:
        pass
print(outs)

如果数字总是在字符串的开头,您可能会考虑一些类似于“代码> OutString=String [0,3] 。

< p>您可以用正则表达式来做。这很简单:

import re
regularExpression = "[^\d-]*(-?[0-9]+).*"
line = "some text -123 some text"
m = re.search(regularExpression, line)
if m:
    print(m.groups()[0])
此正则表达式提取文本中的第一个数字。它将
'-'
视为数字的一部分。如果不希望将此正则表达式更改为此正则表达式:
“[^\d-]*([0-9]+).*”