[英]Custom format for list output in Python
我已經審查了其他問題,但沒有具體找到這個答案。 我正在制作一個程序來讀取包含多行數據的文本文件,並量化相似的行。 下面是我正在使用的代碼,但我正在嘗試以自定義格式或至少單獨打印 output。 我該如何改進?
理想情況下,我想要一個 output,例如:
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
。
Output:
{'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}")
Output:
B12-H-BB-DD: x3
A2-W-FF-DIN: x2
A2-FF-DIN: x1
C1-GH-KK-LOP: x1
使用來自 collections 的計數器的更多 Pythonic 方式:
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}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.