简体   繁体   中英

How do I remove newline from my key in a dictionary?

I have a file I am reading from and putting it into a dictionary. How do I remove the new line from the key?

def main():

    # Set up empty dictionary
    counter = {}

    # open text file
    my_file = open("WorldSeriesWinners.txt", "r")
    words = my_file.readlines()

    # Add each unique word to dictionary with a counter of 0
    unique_words = list(set(words))
    for word in unique_words:
        counter[word] = 0

    # For each word in the text increase its counter in the dictionary
    for item in words:
        counter[item] += 1

    return counter

counter = main()
print(counter)

OUTPUT:

{'Cleveland Indians\\n': 2, 'Pittsburgh Pirates\\n': 5, 'St. Louis Cardinals\\n': 10, 'New York Giants\\n': 5, 'Cincinnati Reds\\n': 5, 'Boston Americans\\n': 1, 'Chicago White Sox\\n': 3, 'Toronto Blue Jays\\n': 2, 'Detroit Tigers\\n': 4, 'NONE\\n': 2, 'Boston Red Sox\\n': 6, 'Minnesota Twins\\n': 2, 'Kansas City Royals\\n': 1, 'Chicago Cubs\\n': 2, 'Baltimore Orioles\\n': 3, 'Arizona Diamondbacks\\n': 1, 'Philadelphia Phillies': 1, 'Los Angeles Dodgers\\n': 5, 'Brooklyn Dodgers\\n': 1, 'Florida Marlins\\n': 2, 'Washington Senators\\n': 1, 'New York Yankees\\n': 26, 'Philadelphia Athletics\\n': 5, 'Boston Braves\\n': 1, 'New York Mets\\n': 2, 'Atlanta Braves\\n': 1, 'Anaheim Angels\\n': 1, 'Philadelphia Phillies\\n': 1, 'Oakland Athletics\\n': 4, 'Milwaukee Braves\\n': 1}

Just use the replace function when defining your key. See below:

def main():

    # Set up empty dictionary
    counter = {}

    # open text file
    my_file = open("WorldSeriesWinners.txt", "r")
    words = my_file.readlines()

    # Add each unique word to dictionary with a counter of 0
    unique_words = list(set(words))
    for word in unique_words:
        word_no_lines = word.replace('\n', '')
        counter[word_no_lines] = 0

    # For each word in the text increase its counter in the dictionary
    for item in words:
        item_no_lines = item.replace('\n', '')
        counter[item_no_lines] += 1

    return counter

counter = main()
print(counter)

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