【问题标题】:Python exercise with url and string counting带有 url 和字符串计数的 Python 练习
【发布时间】:2013-11-08 19:21:16
【问题描述】:

我必须做的练习有点问题: 基本上任务是打开一个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,缺少其他出现和整个计数值. 我究竟做错了什么?提前致谢

【问题讨论】:

标签: python


【解决方案1】:

您没有正确附加到字典。

正确的方式是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}     

【讨论】:

    【解决方案2】:

    或者你可以使用 Collections.Counter :

    >>> from collections import Counter
    >>> words = ['apple', 'apple', 'pear', 'banana']
    >>> Counter(words)
    Counter({'apple': 2, 'pear': 1, 'banana': 1})
    

    【讨论】:

      【解决方案3】:

      不要忘记列表和字典理解。它们在处理更大的数据集时可能非常有效(特别是如果您在示例中分析大型网页)。归根结底,如果您的数据集很小,人们可能会争辩说 dict 理解语法更简洁/更 Python 等。

      所以在这种情况下,我会使用类似的东西:

      result = {word : decoded.count(word) for word in words}
      

      【讨论】:

        猜你喜欢
        • 2020-08-27
        • 2015-04-26
        • 1970-01-01
        • 2013-11-06
        • 1970-01-01
        • 1970-01-01
        • 2021-02-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多