下面是我的代码:
# Get the name of the file and open it
name = input("Enter file:")
handle = open(name)
# Count word frequency
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
# Find the most common word
bigcount = None
bigword = None
for word.count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
# All done
print(bigword, bigcount)
当我调用它并输入消息并按enter键时,出现AttributeError并说:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-500085f286fd> in <module>
13 bigcount = None
14 bigword = None
---> 15 for word.count in counts.items():
16 if bigcount is None or count > bigcount:
17 bigword = word
AttributeError: 'str' object attribute 'count' is read-only
我应该做什么来修复我的代码?什么是"只读"?STR对象属性?
在您的示例代码中:word
是一个字符串,如果您的代码中嵌套的for
循环至少执行一次。
for line in handle:
words = line.split()
for word in words:
...
一个字符串有一个方法count()
(用于计算连续次数的子字符串可以在字符串中找到),并通过使用word.count
作为你的循环变量在for word.count in counts.items():
,你的代码试图覆盖word
上的.count
,它不能。在两个名称之间使用句号是在告诉编译器你正在试图访问某个对象的属性,在类的文档中有更多的介绍。
回答你的问题:这不是关于"read-only"的错误。str object attribute',试图更改str
类型对象的只读属性是错误的。像.count()
这样的str
类型的方法不能被其他东西覆盖,它是只读的。
你可能想要:
for word, count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
你应该小心在你的代码中使用和重用不同含义的变量名。
另外,请注意,您永远不会关闭您的文件(handle
),您应该查看使用上下文管理器(with ...:
),并且您正在为可以在几行中完成的任务做大量的数据移动。
例如:
from collections import defaultdict
name = input("Enter file: ")
words = defaultdict(int)
with open(name) as f:
for line in f:
for word in line.split():
words[word] += 1
most_frequent_word = max(words, key=lambda word: words[word])
print(most_frequent_word, words[most_frequent_word])
当然,这和你自己的代码,没有考虑到间断,大写等。