有人可以帮忙吗?我是这个网站的新手,也是python的新手。 我必须编写一个脚本来获取IP的最后两个oct并进行一些计算以使它们与端口号匹配。 我一直在撞墙,试图很难获得IP的最后两个值。 任何帮助都会很棒。这是我的代码:
import sys
import re
t= open('fileD.txt','r')
t = t.readline()
s = t.split(";")
holder = []
wordlist = {}
print s
for c in s:
wordlist[c.split()[0]] = c.split()
print c
with open('filex.txt','w') as x:
x = x.write(c)
x = open('filek.txt','w')
with open ('filex.txt', 'r') as f:
column = 0
for line in f:
if not re.match('@', line):
line = line.strip()
sline = line.split()
x.write(sline[column] + '\n')
x.close()
sys.exit(0)
这是fileD.txt
:
99413 ;199.189.17.13 9999
99413 ;199.189.17.13 9999
99414 ;199.189.17.14 9999
99414 ;199.189.17.14 9999
99414 ;199.189.17.14 9999
99415 ;199.189.17.15 9999
99415 ;199.189.17.15 9999
99415 ;199.189.17.15 9999
所以,我需要取.17
和.10
并将它们放入计算中以生成99415
,这是一个端口。
答案 0 :(得分:0)
你可以这样做:
file = open("fileD.txt","r")
for line in file: # for example, first line
ipparts = line.split()[1][1:].split(".") # list as ["199","189","17","13"]
thirdgroup = ipparts[2] # "17"
forthgroup = ipparts[3] # "13"
# make here what you want with those values.
file.close()
答案 1 :(得分:0)
您可以使用列表理解:
with open('fileD.txt') as f:
last_two_nums = [line.split()[1][-5:].split('.') for line in f] # [['17', '13'], ['17', '13'], ...]
或强>
with open('fileD.txt') as f:
for line in f:
last_two_nums = line.split()[1][-5:].split('.') # gives for ex: ['17', '13']
# do what you've got to do here
您可以通过last_two_nums[0]
或last_two_nums[1]
访问它们
在进行任何计算之前,请确保将它们从字符串转换为数字
使用int()
或float()