首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从字典中的键中删除换行符?

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

Stack Overflow用户
提问于 2021-11-10 01:49:52
回答 1查看 39关注 0票数 1

我有一个正在读取的文件,并将其放入字典中。如何从键中删除新行?

代码语言:javascript
复制
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)

输出:

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-10 01:53:22

只需在定义密钥时使用replace函数即可。如下所示:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69907085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档