python的应用 | 统计英文单词出现的次数
需求:
统计一个TXT中英文单词出现的次数
完整代码:
#统计一个TXT中英文单词出现的次数 #打开文件并读取内容 with open('D:\\python_data\\file.txt','r')as file: text=file.read() #将文本内容分割成单词,以空格和换行符合为分隔符 words=text.split() #初始化一个空字典用于存储单词计数 word_count={} #遍历单词列表并统计单词出现次数 for word in words: #去除标点符合 word=word.strip('.,?()[]{}"\'') #如有需要,可以转换成小写 #word=word.strip('.,?()[]{}"\'').lower() if word: if word in word_count: word_count[word]+=1 else: word_count[word]=1 for word,count in word_count.items(): print(f'{word}:{count}') # 如果需要将结果保存到文件,可以使用以下代码: with open('word_count.txt', 'w') as output_file: for word, count in word_count.items(): output_file.write(f'{word}: {count}\n')
输出效果如图:
拓展:
根据需求输入单词,统计出现的次数,并输出结果。然后,循环会再次开始,等待下一次输入,如果不需要,则按q退出程序。
#统计一个TXT中英文单词出现的次数 #打开文件并读取内容 with open('D:\\python_data\\file.txt','r')as file: text=file.read() #将文本内容分割成单词,以空格和换行符合为分隔符 words=text.split() #初始化一个空字典用于存储单词计数 word_count={} #遍历单词列表并统计单词出现次数 for word in words: #去除标点符合 word=word.strip('.,?()[]{}"\'') #如有需要,可以转换成小写 #word=word.strip('.,?()[]{}"\'').lower() if word: if word in word_count: word_count[word]+=1 else: word_count[word]=1 # 无限循环直到输入 'q' 退出 while True: # 输入要统计的单词或退出字符 input_word = input("请输入要统计的单词(输入 q 退出): ") # 如果输入为退出字符,则退出循环 if input_word == 'q': break # 获取输入单词的出现次数 count = word_count.get(input_word, 0) # 输出结果 print(f"{input_word} 出现的次数为: {count}")
输出效果如图:
分类:
Python
, Python办公自动化
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)