Count Words in a String (升级版)
题目要求:
read these strings in from a text file and generate a summary.
import os def count_words(file): try: f = open(file, 'r', encoding='UTF-8') except IOError as s: print(s) return None # try,except语句:用来捕获异常,try:尝试执行的代码,except:出现错误的处理 try: buffer = f.read() except: print('Read File Error!') return None (filepath, filename) = os.path.split(file) # 使用os模块的path.split函数获得传入文件的路径名与文件名 f.close() buffer = buffer.lower() # 全部换成小写,以免后面大小写按照不同字符处理 words = buffer.split(' ') # 按空格分割文本,针对英文单词,目前还不知道怎么分割一个字一个字得分割汉字 counts = {} # (),[],{}分别代表元组,列表,字典,这里是创建一个空字典接收后面的循环计数器结果 sumcount = 0 for word in words: counts[word] = counts.get(word, 0) + 1 sumcount = sumcount + 1 # 循环计数器: # dict.get(key, default=None) # key -- 字典中要查找的键。 # default -- 如果指定键的值不存在时,返回该默认值。 # 当word不在words时,返回值是0,当word在words中时,返回+1,以此进行累计计数。 items = list(counts.items()) items.sort(key=lambda x: x[1], reverse=True) # 将字典按value的值进行排序 fileresult = open(os.path.join(filepath, "result.txt"), 'w') # 在传入文件的路径之下,创建一个新的result文件,具有可写的属性 for i in range(5): word, count = items[i] fileresult.write(word) # f.write每次只能传入一个值,有没有更简洁的写法呢?欢迎评论 fileresult.write('\n') fileresult.write(str(count)) fileresult.write('\n') # 调用函数: count_words("C:\\Users\\cccc\\Desktop\\hamlet.txt")
原始文件为:
Oh they say people come say people go
This particular diamond was extra special
And though you might be gone and the world may not know
Still I see you celestial
When I should but I can't let you go
But when I'm cold cold
When I'm cold cold
There's a light that you give me when I'm in shadow
There's a feeling within me an everglow
Like brothers in blood sisters who ride
And we swore on that night we'd be friends 'til we die
But the changing of winds and the way waters flow
Life is short as the falling of snow
And now I'm gonna miss you I know
But when I'm cold cold
In water rolled salt
I know you're with with me and the way you will show
And you're with me wherever I go
And you give me this feeling this everglow
Oh what I wouldn't give for just a moment to hold
Becasue I live for this feeling this everglow
So if you love someone you should let them know
Oh the light that you give me will everglow
结果为:
you
10
i
7
the
6
me
6
i'm
5
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通