用python写代码,删除以abc开头的重复的行
时间: 2023-06-20 07:03:24 浏览: 48
可以使用以下代码实现:
```python
with open('file.txt', 'r') as f:
lines = f.readlines()
new_lines = []
for line in lines:
if not line.startswith('abc') or line not in new_lines:
new_lines.append(line)
with open('file.txt', 'w') as f:
f.writelines(new_lines)
```
这个程序会读取名为 `file.txt` 的文件,并将每一行存储在一个列表中。然后,它会创建一个新的列表 `new_lines`,用于存储没有以 "abc" 开头或者之前没有出现过的行。最后,它会将新的列表写回文件中,从而实现删除以 "abc" 开头的重复行的功能。
需要注意的是,此程序会完全覆盖原始文件,因此建议在运行之前备份原始文件。
相关问题
用python写代码,删除以abc开头的重复的行。把第一行作为标题行,画出折线图
假设我们有一个名为file.txt的文本文件,里面内容如下:
```
abc123
abc456
def123
def456
abc789
ghi123
```
我们可以使用以下代码来删除以abc开头的重复行,并将第一行作为标题行:
```python
import matplotlib.pyplot as plt
with open("file.txt", "r") as f:
lines = f.readlines()
unique_lines = []
for line in lines:
if not line.startswith("abc") or line in unique_lines:
continue
unique_lines.append(line)
# 添加标题行
unique_lines.insert(0, "Title\n")
with open("output.txt", "w") as f:
f.writelines(unique_lines)
# 画折线图
x = []
y = []
with open("output.txt", "r") as f:
for i, line in enumerate(f):
if i == 0: # 跳过标题行
continue
data = line.strip().split(" ")
x.append(int(data[0]))
y.append(int(data[1]))
plt.plot(x, y)
plt.show()
```
这段代码会将符合条件的行写入到名为output.txt的文件中,并画出折线图。注意要先安装Matplotlib库。
写出python代码,用argparse。能在任何文件夹读取Log。具体如下: 1.读取log,当读取到最后一次出现"My name is kitty"时,从下一行开始读 2.删除所有重复的行,只留第一行 3.第一行按照正则规则1分列后,写入新的CSV文件Output 4.从下一行开始按照正则规则2分列后,继续写入新的CSV文件Output 5.读取CSV文件Output 6.把标题行分为4类,第一类是标题为ABC,DFG的2列,第二类是CAT开头的几列,第三类是DOG开头的几列,第四类是Fish开头的几列 7.把4类标题画成曲线图
以下是使用argparse的Python代码实现:
```python
import re
import csv
import os
import matplotlib.pyplot as plt
import argparse
# 正则规则1和2
rule1 = r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}),(.+),(\d+),(\d+),(.+)"
rule2 = r"(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+)"
# 读取log文件
def read_log(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
index = 0
for i, line in enumerate(lines):
if "My name is kitty" in line:
index = i + 1
return lines[index:]
# 删除重复行
def remove_duplicate(lines):
new_lines = []
for line in lines:
if line not in new_lines:
new_lines.append(line)
return new_lines
# 写入CSV文件
def write_csv(lines, output_file):
with open(output_file, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Date', 'Name', 'ID1', 'ID2', 'Content'])
for line in lines:
match = re.match(rule1, line)
if match:
writer.writerow(match.groups())
else:
match = re.match(rule2, line)
if match:
writer.writerow(match.groups())
# 读取CSV文件
def read_csv(file_path):
with open(file_path, 'r') as f:
reader = csv.reader(f)
rows = [row for row in reader]
return rows[1:], rows[0]
# 按照标题分类
def classify_title(headers):
abc_headers = []
cat_headers = []
dog_headers = []
fish_headers = []
for header in headers:
if header.startswith('ABC') or header.startswith('DFG'):
abc_headers.append(header)
elif header.startswith('CAT'):
cat_headers.append(header)
elif header.startswith('DOG'):
dog_headers.append(header)
elif header.startswith('Fish'):
fish_headers.append(header)
return abc_headers, cat_headers, dog_headers, fish_headers
# 画曲线图
def plot_curve(data, title):
x = range(len(data))
plt.plot(x, data)
plt.title(title)
plt.show()
if __name__ == '__main__':
# 创建解析器对象
parser = argparse.ArgumentParser(description='Process log file.')
# 添加参数
parser.add_argument('file_path', metavar='FILE', type=str,
help='path to the log file')
parser.add_argument('--output', metavar='OUTPUT', type=str, default='output.csv',
help='path to the output file')
# 解析参数
args = parser.parse_args()
# 读取log文件
lines = read_log(args.file_path)
# 删除重复行
new_lines = remove_duplicate(lines)
# 写入CSV文件
write_csv(new_lines, args.output)
# 读取CSV文件
data, headers = read_csv(args.output)
# 按照标题分类
abc_headers, cat_headers, dog_headers, fish_headers = classify_title(headers)
# 画曲线图
for header in abc_headers:
index = headers.index(header)
column = [float(row[index]) for row in data]
plot_curve(column, header)
for header in cat_headers:
index = headers.index(header)
column = [float(row[index]) for row in data]
plot_curve(column, header)
for header in dog_headers:
index = headers.index(header)
column = [float(row[index]) for row in data]
plot_curve(column, header)
for header in fish_headers:
index = headers.index(header)
column = [float(row[index]) for row in data]
plot_curve(column, header)
```
运行时,需使用命令行指定log文件路径和输出文件路径,例如:
```bash
python log_processor.py log.txt --output output.csv
```
其中,log.txt为log文件的路径,output.csv为输出文件的路径。如果不指定输出文件路径,则默认为output.csv。