Everything is working properly except the printing of the list, I have tried multiple ways rstrip()
, splitline()
, replace()
, etc. But perhaps I am not using them correctly. I am fairly new to using dictionaries so I would appreciate some guidance for the current problem.
txt file (should already be in a list form):
Shopping List
ITEM 1000: Frozen Burgers
ITEM 1001: Bread
ITEM 1002: Frozen Burgers
ITEM 1003: Mayonnaise
ITEM 1004: Bread
ITEM 1005: Frozen Burgers
ITEM 1006: Mustard
ITEM 1007: Tomato
ITEM 1008: Tomato
Code:
from collections import Counter
def get_items():
print("""Items that repeat twice or more in the lists:
Item Name Repeat Times
------------------------------""")
item_count = Counter()
with open('Shopping_List.txt') as f:
for line in f.readlines()[1:]:
item_count.update([line[11:]])
print('\r',*item_count.most_common(3),sep='\n')
def get_dictionaries(textfile):
items = {}
numbers = {}
FIRST_NUM = 1000
with open(textfile) as f:
for lines in f.readlines()[1:]:
numbers[FIRST_NUM]=lines.lstrip()[11:]
items[lines.lstrip()[11:]]=items.setdefault(lines.lstrip()[11:],0) 1
FIRST_NUM = 1
return items,numbers
get_items()
CodePudding user response:
The proper solution is to use a computer-readable input file format so you don't have to write your own parser.
Here's a quick refactoring to your code, though.
from collections import Counter
def get_items():
print("""Items that repeat twice or more in the lists:
Item Name Repeat Times
------------------------------""")
item_count = Counter()
with open('Shopping_List.txt') as f:
for idx, line in enumerate(f):
if idx == 0:
next
item_count.update([line[11:].rstrip('\n')])
for x in item_count.most_common(3):
print(' {0:16} {1}'.format(*x))
get_items()
I removed the unused function. The main change is .rstrip('\n')
though notice also how the printing and the iterating of the lines are refactored.
CodePudding user response:
You can print the rows like this:
def get_items():
print(
"""Items that repeat twice or more in the lists:
Item Name Repeat Times
------------------------------"""
)
item_count = Counter()
with open("1.txt") as f:
for line in f.readlines()[1:]:
item_count.update([line[11:]])
for item, count in item_count.most_common(): # <--- Here.
print(f"{item.rstrip():>15} {count:>6}")
This prints the following:
Items that repeat twice or more in the lists:
Item Name Repeat Times
------------------------------
Frozen Burgers 3
Bread 2
Mayonnaise 1
Mustard 1
Tomato 1
Tomato 1
CodePudding user response:
you can do a simple check on each string read.
if StringExample[-1:] == "\n":
StringExample = StringExample[:-1]