Python读取文件存入字典时如何去除键中的换行符
问题原因
readlines() 读取文本文件的每一行时,会默认保留行末尾的换行符\n,这些换行符会被直接带到后续生成的字典键中。
修复方案
读取每一行内容时,调用rstrip('\n')方法删除末尾的换行符即可,如果你同时需要去除行首尾的空格、制表符等空白字符,也可以使用strip()方法。
处理后你原输出中同时存在Philadelphia Phillies(无换行)和Philadelphia Phillies\n(有换行)两个独立键的问题也会被修复,两个条目会合并为同一个键,计数累计为2。
最小修改版代码
def main(): # Set up empty dictionary counter = {} # open text file my_file = open("WorldSeriesWinners.txt", "r") # 读取每一行并删除末尾换行符 words = [line.rstrip('\n') for line in my_file.readlines()] my_file.close() # 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)
更简洁的优化版本
可以直接用Python内置的collections.Counter完成计数,不需要手动实现统计逻辑,同时用with语句自动管理文件资源,避免忘记关闭文件导致的资源泄露:
from collections import Counter def main(): with open("WorldSeriesWinners.txt", "r") as f: return Counter(line.rstrip('\n') for line in f) counter = main() print(dict(counter))
内容的提问来源于stack exchange,提问作者I am Jakoby
相关产品推荐
相关产品推荐

