如何从字典中的键中删除换行符?

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

我正在阅读一个文件并将其放入字典中。如何从密钥中删除新行?

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)

输出:

{'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}

只需在定义密钥时使用 replace 函数即可。见下文:

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)