Python - 根据部分字符串打印行

Python - Print line based on partial string

我有 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 匹配,而不是必须将整个预期输出都放在一起

希望这足以结束,对这一切还很陌生,干杯

如果你有一个包含实际 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

我希望这对你有用

完整答案是

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)



假设您的文件有空格而不是制表符:)