Skip to main content
 首页 » 编程设计

带有 url 和字符串计数的 Python 练习

2024年11月01日23xing901022

我必须做的练习有点问题: 基本上,任务是打开一个 url,将其转换为给定的格式,然后计算给定字符串在文本中出现的次数。

import urllib2 as ul  
 
def word_counting(url, code, words): 
    page = ul.urlopen(url) 
    text = page.read() 
    decoded = ext.decode(code) 
    result = {} 
 
    for word in words: 
        count = decoded.count(word) 
        counted = str(word) + ":" + " " + str(count) 
        result.append(counted) 
 
    return finale 

我应该得到的结果类似于“word1: x, word2: y, word3: z”,其中 x、y、z 是出现的次数。但似乎我只得到一个数字,当我尝试运行测试程序时,我得到的结果只有第一次出现时为 9,第二次出现时为 14,第三次出现时为 5,遗漏了其他出现次数和整个计数值. 我究竟做错了什么?提前致谢

请您参考如下方法:

您没有正确地附加到字典。

正确的方法是result[key] = value。

所以对于你的循环它会是

for word in words: 
  count = decoded.count(word) 
  result[word] = str(count) 

一个没有解码但使用.count()的例子

words = ['apple', 'apple', 'pear', 'banana'] 
result= {} 
  for word in words: 
    count = words.count(word) 
    result[word] = count 
 
>>> result 
>>> {'pear': 1, 'apple': 2, 'banana': 1}