问:我在Python解释器中尝试了相同的代码,并得到了{'i':2,'am':2,2,'that':1}的结果。我想念什么吗?非常感谢您的帮助。
word_count.py
#例如word_count(“ I am is I am”)返回一个字典,如:
#{'i':2,'am':2,'that':1}
#小写字符串以使其更容易使用。
#在句子上使用.split()将为您提供单词列表。
#在该列表的for循环中,您将拥有一个单词,可以
#检查是否包含在dict中(使用“ if word in dict”样式的语法)。
#或者它的东西,如word_dict [文字] = 1添加到字典
高清WORD_COUNT (串):string_lower =字符串。lower ()string_list = string_lower 。split ()word_count_list = {}
对于 字 在 string_list :
WORD_COUNT = 1如果字在word_count_list :WORD_COUNT + = 1个word_count_list [字] = word_count中返回word_count_list word_count中(“我是我” )
答:Andreas cormack说他找不到任何错误,但是您的代码中存在逻辑错误。
您的字数不会超过2。
臭虫线是这个
word_count = 1 #每次迭代都重置word_count
让我们看看当字符串为“ foo foo foo ...”时会发生什么。
string_list 将为['foo','foo','foo','foo',...]
foo在string_list->word_count设置为1-> foo在word_count_list->word_count_list现在具有{'foo':1}
foo in- string_list>word_count设置为1-> foo in word_count_list,word_count设置为2->word_count_list现在具有{'foo':2}
foo in- string_list>word_count设置为1-> foo in word_count_list,word_count设置为2->word_count_list现在具有{'foo':2}
随着更多foo的出现,word_count仍然是2。
另外,word_count_list由于它实际上是一个字典并且Python具有称为list的数据类型,所以我不会调用。第一次遇到它们时会感到困惑。
如果需要,可以参考此。
def word_count (string ):
函数中不再使用#字符串,因此无需保持完整性。字=字串。降低()。split ()result = {} #仅存在两种情况:第一次看到或已经看到单词。对于单词在单词:如果字在结果:结果[字] + = 1 #时已经存在的单词。else :结果[单词] = 1
#首次遇到单词时(仅在这种情况下)。
返回结果
答:我的与此类似,只是我将字母的数量放在一个计数变量中,但这是错误的吗?有人可以解释吗?我在解释器中得到了正确的结果:
def word_count (字符串):
string_list = string 。降低()。分裂()计数= 1 count_dict = {}为字母在string_list :如果信在count_dict :count_dict [信] =计数+ 1否则:count_dict [信] =计数返回count_dict