-
Notifications
You must be signed in to change notification settings - Fork 1
/
comparison.py
65 lines (49 loc) · 2.02 KB
/
comparison.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
from bs4 import BeautifulSoup
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from nltk.corpus import stopwords
from sentence_transformers import SentenceTransformer
import requests
import nltk
# Make sure stopwords are downloaded
nltk.download('stopwords')
# Function to get cleaned text from a webpage
def get_cleaned_text(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Extract text from the webpage
text = soup.get_text()
# Remove stopwords
stop_words = set(stopwords.words('english'))
words = nltk.word_tokenize(text)
cleaned_text = " ".join([word for word in words if word not in stop_words])
return cleaned_text
# Semantic comparison function
def semantic_comparison(url1, url2):
# Get the cleaned text
text1 = get_cleaned_text(url1)
text2 = get_cleaned_text(url2)
# Use BERT model for semantic similarity
model = SentenceTransformer('all-MiniLM-L6-v2') # or any other model
embeddings1 = model.encode([text1], convert_to_tensor=True)
embeddings2 = model.encode([text2], convert_to_tensor=True)
# Semantic similarity
semantic_similarity = cosine_similarity(embeddings1, embeddings2)
return semantic_similarity[0][0]
# N-gram comparison function
def ngram_comparison(url1, url2):
# Get the cleaned text
text1 = get_cleaned_text(url1)
text2 = get_cleaned_text(url2)
# TF-IDF Vectorizer with n-gram
vectorizer = TfidfVectorizer(ngram_range=(1,2)) # Unigrams and bigrams
# Transform the text into TF-IDF vectors
tfidf_matrix = vectorizer.fit_transform([text1, text2])
# N-gram similarity
ngram_similarity = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])
return ngram_similarity[0][0]
# Overall comparison function
def compare(url1, url2):
semantic_similarity = semantic_comparison(url1, url2)
ngram_similarity = ngram_comparison(url1, url2)
return semantic_similarity, ngram_similarity