![](/img/trans.png)
[英]Python 2: Using regex to pull out whole lines from text file with substring from another
[英]python: read a file and match string in another file and pull out the lines
数据主文件:
192.168.42.2
192.68.42.12
搜索文件:
1 17.248.154.203 => 7.88Kb 28.6Kb 28.6Kb 28.6KB
192.168.42.12 <= 208b 151Kb 151Kb 151KB
2 a23-58-18-217.deploy.static.akamaitechn => 6.61Kb 8.60Kb 8.60Kb 8.60KB
192.168.42.12 <= 15.0Kb 4.95Kb 4.95Kb 4.95KB
3 a23-207-129-216.deploy.static.akamaitec => 0b 8.09Kb 8.09Kb 8.09KB
192.168.42.12 <= 0b 3.25Kb 3.25Kb 3.25KB
4 17.252.172.5 => 0b 4.92Kb 4.92Kb 4.92KB
192.168.42.2 <= 0b 3.73Kb 3.73Kb 3.73KB
192.168.42.2 <= 0b 3.73Kb 3.73Kb 3.73KB
期望的输出:
192.168.42.12 3.25(示例)
192.168.42.2 3.73
[链接] https://pastebin.com/Ms4TyLMW - 我已根据您的建议更改了我的代码
这就是我得到的!
'192.168.42.12 151
192.168.42.12 4.95
192.168.42.12 3.25
192.168.42.2 3.73
192.168.42.2 3.73
192.168.42.12 5.36
192.168.42.12 705'
@saul
我怎样才能避免打印这个多个相同的数据。我试图在这样的单行打印相同的IP和相应的用法?
'192.168.42.12 2043(总使用量192.168.42.12)
192.168.42.2 123(总使用量192.168.42.2)'
我在文本文件中有两个IP地址。 首先,我需要读取IP地址,然后检查另一个使用IP地址的文件(请参阅上面的问题)。
现在我需要从另一个文件中提取相应的IP和用法。 此代码定位IP和使用的特定位置。 问题是,当我尝试迭代iplist
它始终接受第一个数据的输入,无论文件中的哪个。 提前致谢。
码:
for line in data_consumed:
for element in iplist:
if element in line:
result = line
ip = line[5:-50]
result_ip = ip.replace(" ","")
usage = line[-8:]
d = usage.replace('KB', '')
usage = d.replace('B','')
usage = usage.replace('\n','')
final_usage += float(usage)
try:
final_usage += float(usage)
except ValueError:
pass
megabyte = float(0.000976562)
result_usage = megabyte * final_usage
print result_ip + '\t\t\t' + str(result_usage)
期望的输出:
192.168.42.12 usage(total value)
192.168.42.2 usage(totalvalue)
你可以像代码一样:
strStr = ["192.168.42.2", "192.168.42.12"]
# the "e:\temp\111.txt" is the searching file storage path.
with open(r"e:\temp\111.txt") as f:
lines = f.readlines()
for ii in strStr:
sumResult = 0
for line in lines:
if ii in line:
sumResult += float(line.strip(" ").split(" ")[-1].split("KB")[0])
print(ii, sumResult)
代码结果是:
192.168.42.2 7.46
192.168.42.12 159.2
有一些问题,因为你没有指出匹配条件,只是从行数据中分割出最后一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.