简体   繁体   English

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

[英]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. {'克利夫兰印第安人\\n':2,'匹兹堡海盗\\n':5,'圣。 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}路易斯红雀队\\n':10,'纽约巨人队\\n':5,'辛辛那提红人队\\n':5,'波士顿美国人\\n':1,'芝加哥白袜队\\n':3,'多伦多蓝鸟队\\n':2,'底特律老虎队\\n':4,'无\\n':2,'波士顿红袜队\\n':6,'明尼苏达双城队\\n':2,'堪萨斯城皇家队\\n': 1、'芝加哥小熊队\\n':2、'巴尔的摩金莺队\\n':3、'亚利桑那响尾蛇队\\n':1、'费城费城人队':1、'洛杉矶道奇队\\n':5、'布鲁克林道奇队\\ n': 1, '佛罗里达马林鱼\\n': 2, '华盛顿参议员\\n': 1, '纽约洋基队\\n': 26, '费城田径队\\n': 5, '波士顿勇士队\\n': 1 , '纽约大都会队\\n': 2, '亚特兰大勇士队\\n': 1, '阿纳海姆天使队\\n': 1, '费城费城人队\\n': 1, '奥克兰运动队\\n': 4, '密尔沃基勇士队\\n':1}

Just use the replace function when defining your key.定义密钥时只需使用replace功能。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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