【发布时间】:2021-12-31 22:33:22
【问题描述】:
我有 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 匹配,而不必放置整个预期输出
希望这已经足够了,对这一切还是很陌生,干杯
【问题讨论】:
标签: python file compare output string-matching