str对象‘read-only’属性含义及Python代码报错修复方法
单词频率统计代码报错修复及概念解释
1. str对象的"read-only"属性是什么意思?
Python中的字符串(str)属于不可变数据类型,它的所有内部属性都是只读状态,不允许被修改。你代码里写word.count时,Python会误解为你试图给字符串对象word的count属性赋值,但字符串的属性无法被修改,因此抛出了AttributeError。本质上这是循环变量的语法误用,并非真的要修改字符串属性。
2. 代码修复方法
报错的核心是遍历字典项时的语法错误:counts.items()返回的是(单词, 计数)形式的元组,需要用两个独立变量接收元组内的两个值,而非word.count这种错误写法。
修复后的代码
# 获取文件名并打开 name = input("Enter file:") handle = open(name) # 统计单词频率 counts = dict() for line in handle: words = line.split() for word in words: counts[word] = counts.get(word, 0) + 1 # 找出出现次数最多的单词 bigcount = None bigword = None # 修正循环变量的接收方式 for word, count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count # 输出结果 print(bigword, bigcount)
更简洁的实现方式(可选)
可以使用Python标准库的collections.Counter来简化代码,同时用with语句自动管理文件关闭,更安全高效:
from collections import Counter name = input("Enter file:") with open(name) as handle: counts = Counter() for line in handle: counts.update(line.split()) # 直接获取出现次数最多的单词及其计数 bigword, bigcount = counts.most_common(1)[0] print(bigword, bigcount)
内容的提问来源于stack exchange,提问作者m _
相关产品推荐
相关产品推荐

