我有一个正在读取的文件,并将其放入字典中。如何从键中删除新行?
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}
发布于 2021-11-10 01:53:22
只需在定义密钥时使用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)https://stackoverflow.com/questions/69907085
复制相似问题