-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract_title.py
206 lines (157 loc) · 5.99 KB
/
extract_title.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
from bs4 import BeautifulSoup
from bs4 import NavigableString
from bs4 import Comment
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import requests
import re
import json
import os
import sys
import html
import logging
import os
def remove_punctuation(line):
rule = re.compile(r"[^a-zA-Z0-9\u4e00-\u9fa5]")
line = rule.sub('', line)
return line
def only_word(string):
rule = re.compile(r"[^a-zA-Z\u4e00-\u9fa5]")
string = rule.sub(' ', string)
string = re.sub('\s+', ' ', string)
return string
def remove_regex(string):
regex = ['(', ')', '?', '[', ']', '{', '}', '|', '.', '&', '*', '$']
for c in regex:
string = string.replace(c, '\\' + c)
return string
def surrounded_by_strings(tag):
return (isinstance(tag.next_element, NavigableString)
and isinstance(tag.previous_element, NavigableString))
def excludeSpecial(string):
return re.sub('\s+', ' ', string)
#Main
logging.basicConfig(level=logging.DEBUG,
format='%(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='main.log',
filemode='w')
urls = []
urls = os.listdir("./")
for url in urls:
# url_name = url.replace('.txt', '.html')
try:
soup = BeautifulSoup(open(url, "rb"), "lxml")
[x.extract() for x in soup.find_all('script')]
[x.extract() for x in soup.find_all('style')]
[x.extract() for x in soup.find_all('meta')]
[x.extract() for x in soup.find_all('noscript')]
[x.extract() for x in soup.find_all('footer')]
[x.extract() for x in soup.find_all(text=lambda text: isinstance(text, Comment))]
html_nodes = excludeSpecial(str(soup.body))
#寻找标题
result = list()
temp_stack = list()
title_set = set()
#h标题
h_nodes = soup.find_all(re.compile("^h[1-9]$"))
# for h_node in h_nodes:
# title_set.add(excludeSpecial(str(h_node)))
for h_node in h_nodes:
title_set.add(excludeSpecial(' '.join(h_node.stripped_strings)))
maybe_title_tag = ['strong', 'b', 'em', 'i']
stop_words = set(stopwords.words('english'))
for tag in maybe_title_tag:
tag_nodes = soup.find_all(tag)
for i in tag_nodes:
flag = False
son_text = i.text.strip()
try:
baba_p_text = i.find_parent("p").text.strip()
except:
baba_p_text = ""
try:
pre_node = i.previous_sibling
if pre_node is None or pre_node == '\n':
title_node = i
flag = True
if not only_word(str(pre_node)).strip().isalpha():
# print(str(i))
title_node = i
flag = True
except:
flag = True
try:
baba_div_text = i.find_parent("div").text.strip()
except:
baba_div_text = ""
try:
brother_node = i.next_sibling
if brother_node == '\n':
flag = True
title_node = i
except:
brother_node = ""
if brother_node is not None:
if brother_node.name == "br":
flag = True
title_node = i
if son_text == baba_p_text:
title_node = i.find_parent("p")
flag = True
if son_text == baba_div_text:
title_node = i.find_parent("div")
flag = True
word_num = son_text.count(' ')
if word_num > 10:
flag = False
try:
child = i.contents[0].name
# print(child)
if child in maybe_title_tag:
# print(child)
flag = False
except:
pass
if flag and len(excludeSpecial(son_text)) > 0:
title_set.add(excludeSpecial(' '.join(title_node.stripped_strings)))
if len(title_set) <= 2:
# print("haha")
str_nodes = html_nodes.split('<br/>')
flag = False
for ele in str_nodes:
flag = False
word_num = ele.count(' ')
word_tokens = word_tokenize(ele)
filtered_sentence = [w for w in word_tokens if not w in stop_words]
filtered_sentence = []
for w in word_tokens:
if w not in stop_words:
filtered_sentence.append(w)
title_str = (' '.join(filtered_sentence)).strip()
if word_num > 10:
flag = False
if title_str == title_str.title() and only_word(title_str).isalpha():
flag = True
if ele.title() == ele and only_word(ele).isalpha():
flag = True
if ele.upper() == ele and only_word(ele).isalpha():
# print(ele)
flag = True
if flag and len(only_word(ele).strip()) > 0:
# print(ele + str(len(ele)))
# logging.
# print(type(title_node))
title_set.add(excludeSpecial(ele))
title_list = []
for title in list(title_set):
if (len(only_word(title)) > 15) and (len(only_word(title)) < 100):
title_list.append(only_word(title))
# title_list = '\n'.join(title_list)
with open('./no_title.txt', "a", encoding="utf8") as f:
# print("ok")
if len(title_list) < 3:
f.write(url+'\n')
except:
print(url)
#