首先,我需要此檔案中所有唯一 IP 的串列。
這是我在 python 中讀取的檔案的一部分:
[node1] - 190.223.252.106 - 用戶成功登錄
[node2] - 239.84.157.20 - 用戶個人資料圖片上傳成功
[node2] - 87.130.185.37 - 用戶成功登錄
[node6] - 210.155.211.219 - 用戶支付成功
[node5] - 64.103.198.103 - 用戶成功登錄
我的代碼:
def UniqueIP(fileparm):
counter = 0
input_file = open(fileparm, 'r')
file_contents = input_file.read()
input_file.close()
ip_list = file_contents.split()
unique_ip = set(ip_list)
for ip in unique_ip:
counter = 1
print(str(counter) ': ' str(ip) "\n")
我有一個良好的開端,但我的輸出如下所示。我主要獲取 IP,但有時也會獲取其余內容的隨機片段。我只想能夠拆分“-”并僅獲取 IP 作為輸出。
29: 191.219.189.162
30:[節點3]
31: 21.147.6.59
32: 55.160.104.8
uj5u.com熱心網友回復:
您需要遍歷每一行:
unique_ips = set()
with open("path/to/file", "r", encoding="utf-8") as file:
for line in file:
line_parts = line.split("-", maxsplit=2)
if len(line_parts) > 2:
ip = line_parts[1]
# Maybe you'd want to check if it's an IP here
# if is_ip(ip):
unique_ips.add(ip)
然后你可以迭代這個集合
for index, ip in enumerate(unique_ips):
print(f"{index 1}: {ip}")
在將 IP 添加到集合之前,我還會驗證它實際上是一個 IP - 它恰好有 4 個位元組(0 到 255 之間),由一個點分隔:
def is_ip(some_str):
try:
bvalues = list(map(int, some_str.split(".")))
except ValueError:
# Some of the stuff couldn't be parsed into int
return False
return all(0<=val<=255 for val in bvalues) and len(bvalues) == 4
(只需確保在其余代碼之前宣告此函式)
uj5u.com熱心網友回復:
如果行總是相同的,-在ip地址前后都有一個,在那個位置,那么你可以使用split特定的字符,選擇適當的元素,然后strip洗掉多余的空格
x = "node1] - 190.223.252.106 - User Successful Login"
x.split('-')[1].strip()
# 190.223.252.106
但是,如果有更多變化,最好使用正則運算式來專門匹配 IP 地址。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/375393.html
下一篇:如何使用C替換文本檔案中的字符?
