本方法是基于文本密度的方法,最初的想法来源于哈工大的《基于行块分布函数的通用网页正文抽取算法》,本文基于此进行一些小修改。
约定:
本文基于网页的不同行来进行统计,因此,假设网页内容是没有经过压缩的,就是网页有正常的换行的。
有些新闻网页,可能新闻的文本内容比较短,但其中嵌入一个视频文件,因此,我会给予视频较高的权重;这同样适用于图片,这里有一个不足,应该是要根据图片显示的大小来决定权重的,但本文的方法未能实现这一点。
由于广告,导航这些非正文内容通常以超链接的方式出现,因此文本将给予超链接的文本权重为零。
这里假设正文的内容是连续的,中间不包含非正文的内容,因此实际上,提取正文内容,就是找出正文内容的开始和结束的位置。
步骤:
首先清除网页中CSS,Javascript,注释,Meta,Ins这些标签里面的内容,清除空白行。
计算每一个行的经过处理的数值(1)
计算上面得出的每行文本数的最大正子串的开始结束位置
其中第二步需要说明一下:
对于每一行,我们需要计算一个数值,这个数值的计算如下:
一个图片标签img,相当于出现长度为50字符的文本 (给予的权重),x1,
一个视频标签embed,相当于出现长度为1000字符的文本, x2
一行内所有链接的标签 a 的文本长度 x3 ,
其他标签的文本长度 x4
每行的数值 = 50 * x1其出现次数 + 1000 * x2其出现次数 + x4 – 8
//说明, -8 因为我们要计算一个最大正子串,因此要减去一个正数,至于这个数应该多大,我想还是按经验来吧。
完整代码
代码如下:
#coding:utf-8
import re
def remove_js_css (content):
""" remove the the javascript and the stylesheet and the comment content (<script>....</script> and ) """
r = re.compile(r'''
s = r.sub ('',content)
r = re.compile(r'''
s = r.sub ('', s)
r = re.compile(r'''''', re.I|re.M|re.S)
s = r.sub('',s)
r = re.compile(r'''
s = r.sub('',s)
r = re.compile(r'''
s = r.sub('',s)
return s
def remove_empty_line (content):
"""remove multi space """
r = re.compile(r'''^\s+$''', re.M|re.S)
s = r.sub ('', content)
r = re.compile(r'''\n+''',re.M|re.S)
s = r.sub('\n',s)
return s
def remove_any_tag (s):
s = re.sub(r''']+>''','',s)
return s.strip()
def remove_any_tag_but_a (s):
text = re.findall (r''']*>(.*?)''',s,re.I|re.S|re.S)
text_b = remove_any_tag (s)
return len(''.join(text)),len(text_b)
def remove_image (s,n=50):
image = 'a' * n
r = re.compile (r'''''',re.I|re.M|re.S)
s = r.sub(image,s)
return s
def remove_video (s,n=1000):
video = 'a' * n
r = re.compile (r'''
s = r.sub(video,s)
return s
def sum_max (values):
cur_max = values[0]
glo_max = -999999
left,right = 0,0
for index,value in enumerate (values):
cur_max += value
if (cur_max > glo_max) :
glo_max = cur_max
right = index
elif (cur_max cur_max = 0
for i in range(right, -1, -1):
glo_max -= values[i]
if abs(glo_max left = i
break
return left,right+1
def method_1 (content, k=1):
if not content:
return None,None,None,None
tmp = content.split('\n')
group_value = []
for i in range(0,len(tmp),k):
group = '\n'.join(tmp[i:i+k])
group = remove_image (group)
group = remove_video (group)
text_a,text_b= remove_any_tag_but_a (group)
temp = (text_b - text_a) - 8
group_value.append (temp)
left,right = sum_max (group_value)
return left,right, len('\n'.join(tmp[:left])), len ('\n'.join(tmp[:right]))
def extract (content):
content = remove_empty_line(remove_js_css(content))
left,right,x,y = method_1 (content)
return '\n'.join(content.split('\n')[left:right])
代码 从最后一个函数开始调用。

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
