Text-Processing

計算任務前後提供 給 Python 腳本的行數

  • August 19, 2018

輸入:

{"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)

所以我正在尋找的是如何編輯我的腳本來計算提供給腳本的行數beforeafter

在您的腳本中稍作修改:

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)

引用自:https://unix.stackexchange.com/questions/463430