我有 2 個檔案,我想相互檢查并拉出它們所在的行。
我試圖用正則運算式來做,但我一直收到這個錯誤,假設這是因為我正在訪問一個檔案而不是直接顯示一個字串
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\re.py", line 248, in finditer
return _compile(pattern, flags).finditer(string)
TypeError: expected string or bytes-like object
這就是我用于正則運算式搜索的內容
regex = r"\d(.*(10.0.0.0).*)"
with open('test1.txt', 'r') as file1:
test = file1.read().splitlines()
matches = re.finditer(regex, test)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
我也試過這個,但仍然出現錯誤
with open("test1.txt") as file1, open("test2") as file2:
st = set(map(str.rstrip,file1))
for line in file2:
spl = line.split(None, 1)[0]
if spl in st:
print(line.rstrip())
錯誤是
IndexError: list index out of range
我正在嘗試將 IP 串列與路由器的輸出相匹配,因此 test2 檔案將如下所示
10.0.0.0/8
11.0.0.0/8
12.0.0.0/8
13.0.0.0/8
路由器輸出看起來像
1 X test 10.0.0.0/8 nov/19/2021 13:03:08
2 X test 11.0.0.0/8 nov/19/2021 13:03:08
3 X test 12.0.0.0/8 nov/19/2021 13:03:08
4 X test 13.0.0.0/8 nov/19/2021 13:03:08
我希望路由器的整條線路僅與 ??IP 匹配,而不必放置整個預期輸出
希望這足以讓一切順利,對這一切仍然很陌生,干杯
uj5u.com熱心網友回復:
完整答案是
with open("router_output.txt") as file1, open("list_of_ips.txt") as file2:
ips_to_keep = file2.read().splitlines()
router_lines = file1.read().splitlines()
ips_to_keep = [" " ip " " for ip in ips_to_keep]
for line in router_lines:
if any(ip in line for ip in ips_to_keep):
print(line)
假設您的檔案有空格而不是制表符:)
uj5u.com熱心網友回復:
如果您有一個包含實際 IP 的檔案,并且不需要正則運算式,那么您可以執行以下操作
my_str = """
1 X test 10.0.0.0/8 nov/19/2021 13:03:08
2 X test 11.0.0.0/9 nov/19/2021 13:03:08
3 X test 12.0.0.0/12 nov/19/2021 13:03:08
4 X test 13.0.0.0/2 nov/19/2021 13:03:08
5 X test 555.0.0.0/2 nov/19/2021 13:03:08 #expecting this to not be printed
"""
keep_ips = [' 10.0.0.0/8 ', ' 11.0.0.0/9 ', ' 12.0.0.0/12 ', ' 13.0.0.0/2 ']
for line in my_str.split('\n'):
if any(ip in line for ip in keep_ips):
print(line)
我在中添加了空格填充,keep_ips否則你可以匹配類似的東西113.0.0.0/25,因為它包含子字串13.0.0.0/2
您可以重構此代碼以從路由器讀取行,然后讀取 IP 行,在 IP 的任一端添加空格,然后使用此邏輯,使用 any
我希望這對你現在有用
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/365668.html
