写出python代码,用def,用argparse。能在任何文件夹读取Log。具体如下: 1.读取log,当读取到最后一次出现"My name is kitty"时,从下一行开始读 2.删除所有重复的行,只留第一行 3.逐行写入csv 4.第1行按照正则规则1提取单词,然后分列,分列后才知道有多少列,分列符号也不知道有几个空格。 5.从第2行开始按照正则规则2分列后,才知道有多少列,分列符号也不知道有几个空格。 6.读取CSV文件Output 7.把标题行分为4类,第一类是标题为ABC,DFG,TBC,DHHG,lop,kki的6列,第二类是CAT开头的几列,第三类是DOG开头的几列,第四类是Fish和food开头的几列 8.把4类标题画成4个曲线图,在一张画布上,标注每条线的标题
时间: 2024-03-10 13:47:10 浏览: 21
以下是可能的Python代码,使用了argparse和pandas库:
```python
import argparse
import pandas as pd
import re
import matplotlib.pyplot as plt
# 定义正则表达式
regex1 = r"\b(\w+)\b" # 正则规则1
regex2 = r"(\s+)" # 正则规则2
# 定义参数解析器
parser = argparse.ArgumentParser(description="Parse log and generate CSV and plots")
parser.add_argument("input_file", help="Input log file path")
parser.add_argument("output_file", help="Output CSV file path")
args = parser.parse_args()
# 读取log文件
with open(args.input_file, "r") as f:
lines = f.readlines()
# 找到"My name is kitty"最后一次出现的位置
last_kitty_index = len(lines) - 1
for i in range(len(lines) - 1, -1, -1):
if "My name is kitty" in lines[i]:
last_kitty_index = i
break
# 从下一行开始读取
lines = lines[last_kitty_index + 1:]
# 删除重复行,只留第一行
lines = list(set(lines))
# 写入CSV文件
with open(args.output_file, "w") as f:
# 处理第一行
first_line = lines[0]
words = re.findall(regex1, first_line)
num_cols = len(words)
# 分列并写入CSV
cols = ["col{}".format(i + 1) for i in range(num_cols)]
df = pd.DataFrame([words], columns=cols)
df.to_csv(f, index=False)
# 处理剩余行
for line in lines[1:]:
words = re.split(regex2, line.strip())
num_cols = len(words) // 2
# 分列并写入CSV
cols = ["col{}".format(i + 1) for i in range(num_cols)]
df = pd.DataFrame([words[::2]], columns=cols)
df.to_csv(f, header=False, index=False)
# 读取CSV文件
df = pd.read_csv(args.output_file)
# 按标题分类
abc_cols = df.columns[df.columns.str.match("ABC|DFG|TBC|DHHG|lop|kki")]
cat_cols = df.columns[df.columns.str.match("CAT")]
dog_cols = df.columns[df.columns.str.match("DOG")]
fish_cols = df.columns[df.columns.str.match("Fish|food")]
# 画曲线图
plt.figure(figsize=(10, 8))
for cols, title in [(abc_cols, "ABC, DFG, TBC, DHHG, lop, kki"), (cat_cols, "CAT"), (dog_cols, "DOG"), (fish_cols, "Fish, food")]:
plt.plot(df[cols], label=title)
plt.legend()
plt.show()
```
注意,这段代码可能需要根据实际情况进行微调,例如正则表达式和标题分类的规则。