Specified from text in python如何挖矿?
How to mine Specified from text in python?
我有一个程序的输出文本,如:
------------
Action specified: GetInfo
Gathering information...
Reported chip type: 2307
Reported chip ID: 98-DE-94-93-76-50
Reported firmware version: 1.08.10
------------
但我必须只 Reported chip type: value "2307"
保存在一个变量中。
怎么可能?
假设您可以读取文件并将其读入名为 text
:
的变量中
for line in text:
if line.startswith("Reported chip type:"):
_, chiptype = line.split(':')
break
print chiptype
这会将 "Reported chip type:" 的值的第一个实例放入 chiptype
。
您的输出如下所示:
2307
注意有一个前导 space。如果您知道它始终是 int
,我们可以将其转换为 int
,您可以这样做:chiptype = int(chiptype)
。如果它只是一个字符串,你可以去掉前导 space: chiptype = chiptype.strip()
你通常会用 regex
做这样的事情
import re
match = re.search('Reported chip type:\s(?P<chip_type>\d+)', my_text)
chiptype = int(match.group('chip_type'))
>>> print chiptype
2307
虽然在你的情况下,它可能很简单,只需要使用几个 splits:
chiptype = int(my_text.split('Reported chip type:', 1)[-1].split('\n')[0].strip())
我有一个程序的输出文本,如:
------------
Action specified: GetInfo
Gathering information...
Reported chip type: 2307
Reported chip ID: 98-DE-94-93-76-50
Reported firmware version: 1.08.10
------------
但我必须只 Reported chip type: value "2307"
保存在一个变量中。
怎么可能?
假设您可以读取文件并将其读入名为 text
:
for line in text:
if line.startswith("Reported chip type:"):
_, chiptype = line.split(':')
break
print chiptype
这会将 "Reported chip type:" 的值的第一个实例放入 chiptype
。
您的输出如下所示:
2307
注意有一个前导 space。如果您知道它始终是 int
,我们可以将其转换为 int
,您可以这样做:chiptype = int(chiptype)
。如果它只是一个字符串,你可以去掉前导 space: chiptype = chiptype.strip()
你通常会用 regex
做这样的事情import re
match = re.search('Reported chip type:\s(?P<chip_type>\d+)', my_text)
chiptype = int(match.group('chip_type'))
>>> print chiptype
2307
虽然在你的情况下,它可能很简单,只需要使用几个 splits:
chiptype = int(my_text.split('Reported chip type:', 1)[-1].split('\n')[0].strip())