推荐答案
测试一下
题目
Suppose there is a logfile
a. The output messages should be ERROR level and theirMESSAGE_CONTENT should contain “NVIDIA_SOC”
b. Sorted the output order by MODULE_TYPE number
c. Use any script language you like.
参考答案与知识点
参考答案
使用Python实现,首先按行读取日志文件,对于每行,使用正则表达式 r'^(ERROR|WARNING|INFO)_TYPE(\d+)_(.*)$' 提取三个分组。根据要求,只保留LEVEL为'ERROR'且MESSAGE_CONTENT包含'NVIDIA_SOC'的行(注意区分大小写,完全匹配大小写敏感)。然后提取TYPE后的数字作为排序键,按整数值升序排序。最后打印出每行原始内容(或按要求格式输出,题目未明确指定输出格式,示例中未给出输出样例,一般直接打印原始行)。
代码:
import re
def printErrors(logPath):
pattern = re.compile(r'^(ERROR)_TYPE(\d+)_(.*)$')
entries = []
with open(logPath, 'r') as f:
for line in f:
line = line.strip()
m = pattern.match(line)
if m:
level = m.group(1)
type_num = int(m.group(2))
content = m.group(3)
if 'NVIDIA_SOC' in content:
entries.append((type_num, line))
entries.sort(key=lambda x: x[0])
for _, line in entries:
print(line)
注意:必须严格匹配格式,忽略包含空格或格式不规范的异常行,如示例中的'ERROR TYPE12 NVIDIA SOC'应被忽略。另外,MESSAGE_CONTENT中的“NVIDIA_SOC”必须连续且大小写敏感,'Nvidia_soc'不匹配。排序按数字,而非字符串,需转换为int。
涉及知识点
- 正则表达式提取分组
- 文件逐行读取
- 条件过滤与大小写敏感
- sorted函数排序
- 字符串解析与int转换