python - 如何获得书 "Web Scraping with Python: Collecting Data from the Modern Web"第 7 章数据标准化部分中的相同结果

标签 python python-2.7 web-scraping ordereddictionary python-collections

Python版本:2.7.10

我的代码:

# -*- coding: utf-8 -*-

from urllib2 import urlopen
from bs4 import BeautifulSoup
from collections import OrderedDict
import re
import string

def cleanInput(input):
    input = re.sub('\n+', " ", input)
    input = re.sub('\[[0-9]*\]', "", input)
    input = re.sub(' +', " ", input)
    # input = bytes(input, "UTF-8")
    input = bytearray(input, "UTF-8")
    input = input.decode("ascii", "ignore")

    cleanInput = []
    input = input.split(' ')

    for item in input:
        item = item.strip(string.punctuation)
        if len(item) > 1 or (item.lower() == 'a' or item.lower() == 'i'):
            cleanInput.append(item)
    return cleanInput

def ngrams(input, n):
    input = cleanInput(input)
    output = []

    for i in range(len(input)-n+1):
        output.append(input[i:i+n])
    return output

url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
html = urlopen(url)
bsObj = BeautifulSoup(html, 'lxml')
content = bsObj.find("div", {"id": "mw-content-text"}).get_text()
ngrams = ngrams(content, 2)
keys = range(len(ngrams))
ngramsDic = {}
for i in range(len(keys)):
    ngramsDic[keys[i]] = ngrams[i]
# ngrams = OrderedDict(sorted(ngrams.items(), key=lambda t: t[1], reverse=True))
ngrams = OrderedDict(sorted(ngramsDic.items(), key=lambda t: t[1], reverse=True))


print ngrams
print "2-grams count is: " + str(len(ngrams))

我最近按照书 Web Scraping with Python: Collecting Data from the Modern Web 学习如何进行网页抓取,而在第 7 章数据规范化部分中,我首先按照书中显示的方式编写代码,并从终端收到错误:

Traceback (most recent call last):
  File "2grams.py", line 40, in <module>
    ngrams = OrderedDict(sorted(ngrams.items(), key=lambda t: t[1], reverse=True))
AttributeError: 'list' object has no attribute 'items'

因此,我通过创建一个新字典来更改代码,其中实体是 ngrams 列表。但我得到了完全不同的结果:

enter image description here

问题:

  1. 如果我想得到书中所示的结果( where sorted by values and the frequency ),我应该编写自己的行来计算每个 2-gram 的出现次数,还是书中的代码已经具有该功能(书中的代码是 python 3 代码)? book sample code on github
  2. 我输出的频率与作者的有很大不同,例如[u'Software', u'Foundation']出现了37次,但没有出现40次。造成这种差异的原因是什么(可能是我的代码错误)?

书籍截图:

Book Screenshot1 Book Screenshot2

最佳答案

本章也出现错误,因为 ngrams 是一个列表。我将它转换为字典并且它有效

ngrams1 = OrderedDict(sorted(dict(ngrams1).items(), key=lambda t: t[1], reverse=True))

关于python - 如何获得书 "Web Scraping with Python: Collecting Data from the Modern Web"第 7 章数据标准化部分中的相同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32811790/

相关文章:

python - 抽象在编程中意味着什么?

测量时间的 Python 上下文管理器

python - 在 Seaborn JointGrid KDE 边缘图上重新缩放轴

web-scraping - 如何限制BeautifulSoup找到的元素数量?

php - 如何使用 php cURL 库绕过 Oracle ADF 环回脚本来编写网站脚本?

python - SSL.SSLError : [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed Python

Python - 从字典中分配和更改列表

python - 如何在 Python 2.7 中创建 Lambda 函数来创建、重新启动、删除、修改 ElastiCache Redis?

python - 试图创建只读属性属性 - getter 返回初始化值,直接访问返回更改后的值

c# - 如何使用 selenium 从工具提示中抓取文本?页面不包含工具提示 html