计算任务前后提供给 Python 脚本的行数

计算任务前后提供给 Python 脚本的行数

输入:

{"case":"0901","emailed":"yes","vote":1,"accepted":"no"},
{"case":"0908","emailed":"yes","vote":8,1"accepted":"yes"},
{"case":"0911","emailed":"no","vote":10,1"accepted":"yes"},
{"case":"0090","emailed":"yes","vote":3,1"accepted":"no"},

编写脚本来接受输入,即使它如下所示:

{"case":"0901","emailed":"yes","vote":1,"accepted":"no"},{"case":"0908","emailed":"yes","vote":8,1"accepted":"yes"},{"case":"0911","emailed":"no","vote":10,1"accepted":"yes"},{"case":"0090","emailed":"yes","vote":3,1"accepted":"no"},

输出

{'case': '0901', 'vote': 1, 'accepted': 'no', 'emailed': 'yes'}
{'case': '0090', 'vote': 3.1, 'accepted': 'no', 'emailed': 'yes'}
Lines Before: 4
Lines After: 2
4.1

我的脚本

import sys, re, ast
with open(sys.argv[1], 'r') as f:
    items = ast.literal_eval(re.sub(r"(\d+),(\d+)", "\\1.\\2,", f.read().replace('\n','')))
    sum = 0
    for d in items:
        if d['emailed'] == 'yes' and d['accepted'] == 'no':
            sum += d['vote']
            print(d)
print(sum)

所以我正在寻找的是如何编辑我的脚本来计算提供给脚本的行数before并且after

答案1

对您的脚本进行一些修改:

import sys, re, ast
with open(sys.argv[1], 'r') as f:
    items = re.findall(r'\{.+?\}', re.sub(r"(\d+),(\d+)", "\\1.\\2,", f.read().replace('\n','')))
    items = [ast.literal_eval(i) for i in items]
    sum = 0
    d_qty = 0
    for d in items:
        if d['emailed'] == 'yes' and d['accepted'] == 'no':
            sum += d['vote']
            d_qty += 1
            print(d)
print('Lines Before: {}'.format(len(items)))
print('Lines After: {}'.format(d_qty))
print(sum)

相关内容