繁体   English   中英

从文本文件读取的行中提取值

[英]extract value from line read from text file

我想使用此代码从文件读取的行中提取带宽的值

  try:
        s1 = open(argv[1], "r")
  except IOError:
        print("server1: fopen");
        sys.exit(-1); 

 lines1 = s1.readlines()
 line1 = lines1[c]
 print line1
 f1 = re.split('.Bytes.*', line1)
 print f1

该行包含此表达式

[  4]  0.0- 1.0 sec   218 KBytes  1.79 Mbits/sec

print f1

给出这个值

['[  4]  0.0- 1.0 sec   218 ', '\n']

我想读取带有M字母的最后一个数字,然后计算为

if M
  B = 1.79*1000000
else if K
  B = 1.79*1000

并且B必须是浮点数

如何提取上一个值?

您也可以不使用正则表达式。

splitted = filter(None, line1.split())
speed = float(splitted[-2])
unit = splitted[-1]
if "M" in unit:
    B = speed*1000000
else if "K" in unit
    B = speed*1000

让我知道它是如何工作的-我还没有测试过。

暂无
暂无

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

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