【发布时间】:2016-09-15 18:34:06
【问题描述】:
所以我试图找到每个页面的一组特定单词(“shall”“may”“must”等),并将它的出现加起来,我使用的代码:
import requests
from bs4 import BeautifulSoup, SoupStrainer
import re
def levelfour(main_url):
pattern = re.compile(r"\bmay not\b", re.IGNORECASE)
pattern1 = re.compile(r"\bshall\b", re.IGNORECASE)
pattern2 = re.compile(r"\bmust\b", re.IGNORECASE)
pattern3 = re.compile(r"\bprohibited\b", re.IGNORECASE)
pattern4 = re.compile(r"\brequired\b", re.IGNORECASE)
r = requests.get(main_url)
soup = BeautifulSoup((r.content), "html.parser")
results = soup.find('article', {'id': 'maincontent'})
results = results.text.encode("utf-8", "ignore")
total = 0
total1 = 0
total2 = 0
total3 = 0
total4 = 0
m = re.findall(pattern, r.content)
m1 = re.findall(pattern1, r.content)
m2 = re.findall(pattern2, r.content)
m3 = re.findall(pattern3, r.content)
m4 = re.findall(pattern4, r.content)
total += len(m)
total1 += len(m1)
total2 += len(m2)
total3 += len(m3)
total4 += len(m4)
print total, total1, total2, total3, total4
########################################Sections##########################
def levelthree(item2_url):
r = requests.get(item2_url)
for sectionlinks in BeautifulSoup((r.content),"html.parser",parse_only=SoupStrainer('a')):
if sectionlinks.has_attr('href'):
if 'section' in sectionlinks['href']:
href = "http://law.justia.com" + sectionlinks.get('href')
levelfour(href)
########################################Chapters##########################
def leveltwo(item_url):
r = requests.get(item_url)
for sublinks in BeautifulSoup((r.content),"html.parser",parse_only=SoupStrainer('a')):
if sublinks.has_attr('href'):
if 'chapt' in sublinks['href']:
chapterlinks = "http://law.justia.com" + sublinks.get('href')
levelthree(chapterlinks)
print (chapterlinks)
######################################Titles###############################
def levelone(url):
r = requests.get(url)
for links in BeautifulSoup((r.content),"html.parser",parse_only=SoupStrainer('a')):
if links.has_attr('href'):
if 'title-54' in links['href']:
titlelinks = "http://law.justia.com" + links.get('href')
# titlelinks = "\n" + str(titlelinks)
leveltwo(titlelinks)
# print (titlelinks)
###########################################################################
base_url = "http://law.justia.com/codes/idaho/2015/"
levelone(base_url)
当我打印出 total,total1,total2,total3,total4 时,它给出了一个零而不是 [0, 0, 0, 0, 0 ] 我的问题,如何才能适当地找到并累加这个集合的出现或单词?
【问题讨论】:
-
您是否在循环中尝试了 printint
repr(line)并检查了您 m 的后记之一?打印一个中间值通常是解决问题的一种快速方法......如果这不能解决它,请放置一个断点并在调试模式下运行它(pycharm 有一个非常好且易于使用的调试模式)跨度> -
@JoranBeasley 所以当我在循环中运行 repr(line) 时,每行都得到 '\t',当我尝试 str(line) 时,我得到了空白空间。和 m 是 [ ],似乎
re.findall没有从我的results中提取字符串 -
然后尝试查看 r.content
-
@JoranBeasley 如果我的问题没看错,我检查了我的
results并且能够打印出页面的内容。 -
继续,您可以将问题范围缩小到问题所在以及如何通过打印来解决问题....您确定有
<article id="maincontent">的实例吗(尝试打印repr(results))
标签: python regex python-2.7 beautifulsoup frequency