Python中列表输出的自定义格式



我已经复习了其他问题,还没有找到这个答案。我正在制作一个程序来读取具有多行数据的文本文件,并量化类似的行。下面是我的代码,我有工作,但我试图有一个自定义格式的输出,或至少单独打印。我该如何改进呢?

理想情况下,我希望输出如下:

B12-H-BB-DD: x3
A2-W-FF-DIN: x2
A2-FF-DIN: x1
C1-GH-KK-LOP: x1
import collections
a = "test.txt"
line_file = open(a, "r")
print(line_file.readable()) #Readable check.
print(line_file.read()) #Prints each individual line.
#Code for quantity counter.
counts = collections.Counter() #Creates a new counter.
with open(a) as infile:
for line in infile:
for number in line.split():
counts.update((number,))
print(counts) #How can I print these on separate lines, with custom format?
line_file.close()
counts = {}
with open('file.txt') as f:
for line in f:
line = line.strip()
counts[line] = counts.get(line, 0) + 1
print(counts)

如果给定键在结果字典中不存在,则counts.get(line, 0)返回0

输出:

{'B12-H-BB-DD': 3, 'A2-W-FF-DIN': 2, 'A2-FF-DIN': 1, 'C1-GH-KK-LOP': 1}

特别安排:

for key, count in counts.items():
print(f"{key}: x{count}")
输出:

B12-H-BB-DD: x3
A2-W-FF-DIN: x2
A2-FF-DIN: x1
C1-GH-KK-LOP: x1

使用Counter from collections的更python化的方式:

from collections import Counter
with open('file.txt') as f:
lines = [line.strip() for line in f]
counts = Counter(lines)
for key, count in counts.items():
print(f"{key}: x{count}")

最新更新