rihit0 commited on
Commit
5aa1681
·
verified ·
1 Parent(s): 3ed18d2

Upload Текстовый документ.txt

Browse files
Текстовый документ.txt ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import nltk
3
+ from nltk.stem.snowball import SnowballStemmer
4
+ from nltk.tokenize import word_tokenize
5
+ from nltk.corpus import stopwords
6
+
7
+ nltk.download('stopwords')
8
+ nltk.download('punkt')
9
+
10
+ stemmer = SnowballStemmer("russian")
11
+ stopwords_ru = stopwords.words("russian")
12
+
13
+
14
+ def to_lowercase(data):
15
+
16
+ data = data.lower()
17
+ return data
18
+
19
+ def noise_remove(data, remove_numbers=True):
20
+
21
+ data = re.sub(r"(\w+:\/\/\S+)", " ", data)
22
+
23
+
24
+ data = re.sub(r"([^0-9А-Яа-я])", " ", data)
25
+
26
+
27
+ if remove_numbers:
28
+ data = re.sub(r"\d+", " ", data)
29
+ return data
30
+
31
+
32
+ def stemming(words):
33
+ return [stemmer.stem(word) for word in words]
34
+
35
+ def tokenize(text):
36
+ words = text.split()
37
+ for elem in words:
38
+ if len(elem) < 3:
39
+ words.remove(elem)
40
+ stemmed_words = stemming(words)
41
+ return ' '.join(stemmed_words)
42
+
43
+
44
+
45
+ import requests
46
+ from bs4 import BeautifulSoup
47
+ from concurrent.futures import ThreadPoolExecutor
48
+
49
+ themes = ['Одежда', 'Животные', 'Политика', 'IT', 'Новости']
50
+
51
+ def get_links(theme): #Сбор ссылок по каждой из тем начиная с главной страницы
52
+ page = requests.get(f'https://habr.com/ru/search/page1/?q={theme}&target_type=posts&order=relevance').text
53
+ page_soup = BeautifulSoup(page, 'html.parser')
54
+ count_pages = int(page_soup.find_all('div', 'tm-pagination__page-group')[-1].text.split()[0])
55
+ hrefs = []
56
+ for i in range(1, count_pages + 1): #Перебор страниц со списком статей с 1 по последнюю
57
+ print(i)
58
+ page = requests.get(f'https://habr.com/ru/search/page{i}/?q={theme}&target_type=posts&order=relevance').text
59
+ page_s = BeautifulSoup(page, 'html.parser')
60
+ links = page_s.find_all('article', 'tm-articles-list__item')
61
+ hrefs.extend([f'https://habr.com/ru/news/{link["id"]}/' for link in links])
62
+ return hrefs #Возвращаем ссылки статей по данной теме
63
+
64
+ def get_text(href): #Парсинг текста статьи по кадой ранее собранной ссылке
65
+ print(href)
66
+ try:
67
+ pagex = requests.get(href).text
68
+ page_su = BeautifulSoup(pagex, 'html.parser')
69
+ text = page_su.find_all("div", "article-formatted-body article-formatted-body article-formatted-body_version-1")[0].text
70
+ return text
71
+ except:
72
+ return ''
73
+
74
+
75
+ all_texts = []
76
+ for theme in themes:
77
+ print(f'Сбор ссылок по теме {theme} начат')
78
+ hrefs = get_links(theme)
79
+ print(f'Сбор ссылок по теме {theme} закончен')
80
+
81
+ with ThreadPoolExecutor() as executor: #Использую распараллеливание для быстрого сбора
82
+ results = list(executor.map(get_text, hrefs)) #Добавляем текст по текущей теме к списку
83
+ all_texts += results #Добавляем тексты по текущей теме к общему списку текстов
84
+ print('Сбор текстов по ссылкам окончен')
85
+
86
+
87
+ from textblob import TextBlob
88
+
89
+ def ngram(data, from_column, to_column, t):
90
+
91
+ new_columns = [[], [], []]
92
+
93
+ if t == 1:
94
+ for index, row in data.iterrows():
95
+ ngram_object = TextBlob(row[from_column])
96
+ unigrams = ngram_object.ngrams(n=1)
97
+ new_columns[0].append(unigrams)
98
+ bigrams = ngram_object.ngrams(n=2)
99
+ new_columns[1].append(bigrams)
100
+ trigrams = ngram_object.ngrams(n=3)
101
+ new_columns[2].append(trigrams)
102
+
103
+ elif t == 2:
104
+ for index, row in data.iterrows():
105
+ unigrams = [word for word in row[from_column].split()]
106
+ new_columns[0].append(unigrams)
107
+ bigrams = [item for item in
108
+ nltk.bigrams(row[from_column].split())]
109
+ new_columns[1].append(bigrams)
110
+ trigrams = [item for item in
111
+ nltk.trigrams(row[from_column].split())]
112
+ new_columns[2].append(trigrams)
113
+
114
+ data[to_column + ' unigrams'] = new_columns[0]
115
+ data[to_column + ' bigrams'] = new_columns[1]
116
+ data[to_column + ' trigrams'] = new_columns[2]
117
+
118
+ ngram(data, 'Text_clear', 'text ', 2)