简体   繁体   中英

Custom format for list output in Python

I've reviewed other questions and haven't found this answer specifically. I'm making a program to read a text file with multiple rows of data, and to quantify similar rows. Below is my code that I have working, but I'm trying to have the output in a custom format, or at least printed individually. How can I improve on that?

Ideally I'd like an output like:

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) returns 0 if given key does not exist yes in the result dictionary.

Output:

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

Special formating:

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

More Pythonic way using Counter from collections:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM