Search code examples
pythonstringdictionarytext-files

How to remove '\n' from end of strings while using txt files and dictionaries?


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()

Solution

  • 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