2 回答
TA贡献1796条经验 获得超7个赞
这是一个建议(相当冗长以突出显示正在发生的事情):
import csv
events = ["PASSED", "FAILED", "EXCEPTION", "NA", "DEPRECATED"]
# Open files
with open('data.csv', 'r') as csv_in, open('data_out.csv', 'w') as csv_out:
# Initialize csv-reader and -writer
csv_reader, csv_writer = csv.reader(csv_in), csv.writer(csv_out)
# Process header
line_in = next(csv_reader)
line_out = line_in + events
csv_writer.writerow(line_out)
# Process data
for line_in in csv_reader:
line_out = line_in
for event in events:
line_out += [sum(1 if event == entry else 0
for entry in line_in[1:])]
csv_writer.writerow(line_out)
我假设您的数据位于名为data.csv. 你必须调整这一点。我希望它能起作用...
PS:您的示例数据中有拼写错误:DEPRICATED应该是DEPRECATED。这会导致非预期的输出。
没有不必要的辅助变量的更紧凑的版本将如下所示:
import csv
events = ["PASSED", "FAILED", "EXCEPTION", "NA", "DEPRECATED"]
with open('data.csv', 'r') as fin, open('data_out.csv', 'w') as fout:
in_, out = csv.reader(fin), csv.writer(fout)
out.writerow(next(in_) + events)
out.writerows(line + [sum(1 if event == entry else 0 for entry in line[1:])
for event in events]
for line in in_)
TA贡献2021条经验 获得超8个赞
您可以使用Counter来计算特定单词的出现次数。假设您已经打开.csv
文件并存储在字符串中input
:您可以执行以下操作:
from collections import Counter
res_values = ("PASSED", "FAILED", "EXCEPTION", "NA", "DEPRECATED")
input = ("Description,dc1pp1sellv01,dc1pp2sellv01,dc2pp1sellv01\n"
"1.1 Database Placement,PASSED,PASSED,PASSED\n"
"1.2 Use dedicated least privilaged account,PASSED,PASSED,PASSED\n"
"1.3 Diable MySQL history,PASSED,PASSED,FAILED\n"
"2.1 Ensure old passwords is set to 1,PASSED,DEPRICATED,NA")
print('\n'.join(
[line + ',' + ','.join(
[str(Counter(line.split(','))[res])
if i != 0
else res
for res in res_values]
)
for i, line in enumerate(input.split('\n'))]))
我使用列表理解来更好地优化流程(因为文件可能非常大),但这里有另一个更清晰的代码,它执行完全相同的操作:
split = input.split('\n') # Split the input line by line
for i, line in enumerate(split): # For each line of the input
if i == 0: # Write full result name (for the first line)
split[i] += ',' + ','.join(res_values)
else: # Count and write result occurrences
counts = Counter(line.split(','))
for res in res_values:
split[i] += ',' + str(counts[res])
print('\n'.join(split)) # Join the full string
我提出了一个准备执行的解决方案,但出于优化目的,逐行读取文件当然比将其存储在像这里这样的字符串变量中更好。
添加回答
举报