gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:28:03 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com