Python 编程
发布网友
发布时间:2022-04-24 05:48
我来回答
共2个回答
热心网友
时间:2022-04-19 01:50
代码使用python3.x版本,依赖第三方库openpyxl
安装openpyxl命令如下:
pip install openpyxl
python代码如下:
import openpyxl
import re
INPUT_FILE = 'input.txt'
OUTPUT_FILE = 'result.xlsx'
with open(INPUT_FILE, 'r', encoding='utf-8') as f:
wb = openpyxl.Workbook()
ws = wb.active
for line in f:
words = re.split('[,,\n]', line)
vals = words[2:]
for w in vals:
try:
float(w)
except ValueError as e:
words.remove(w)
else:
if words.count(w) > 1:
for i in range(words.count(w)-1):
words.remove(w)
vals = words[2:]
vals.sort(reverse=True)
if len(vals) > 4:
vals = vals[:3] + vals[-1:]
words = words[:2] + vals
ws.append(words)
wb.save(OUTPUT_FILE)
若代码格式有乱,请参照下图:
测试结果:
追问还有 里面的输入错误的语句没写,比如5.6输成5-6
追答
你题目写的不是要删除错误成绩吗?
下面程序修改识别错误成绩,如识别5-6为5.6:
import openpyxl
import re
INPUT_FILE = 'input.txt'
OUTPUT_FILE = 'result.xlsx'
with open(INPUT_FILE, 'r', encoding='utf-8') as f:
wb = openpyxl.Workbook()
ws = wb.active
for line in f:
words = re.split('[,,\n]', line)
vals = words[2:]
for w in vals:
try:
float(w)
except ValueError as e:
if w == '':
words.remove(w)
else:
words.remove(w)
w = w.replace('-', '.')
words.append(w)
finally:
if words.count(w) > 1:
for i in range(words.count(w)-1):
words.remove(w)
vals = words[2:]
vals.sort(reverse=True)
if len(vals) > 4:
vals = vals[:3] + vals[-1:]
words = words[:2] + vals
ws.append(words)
wb.save(OUTPUT_FILE)
程序截图:
测试结果:
热心网友
时间:2022-04-19 03:08
你是老师吧