while len(articles) < n_articles:
# Tambahkan parameter halaman ke URL
url = f"{base_url}page/{page}/"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Ambil semua artikel pada halaman tersebut
for article in soup.find_all('article'):
link = article.find('a', href=True)['href']
articles.append(link)
# Berhenti jika sudah mendapatkan n_articles
if len(articles) >= n_articles:
break
# Jika tidak ada artikel lagi di halaman, hentikan loop
if not soup.find_all('article'):
break
# Lanjutkan ke halaman berikutnya
page += 1
return articles[:n_articles]
def remove_url(text):
if isinstance(text, str):
url = re.compile(r'https?://\S+|www.\S+')
return url.sub(r'', text)
return text # Jika bukan string, kembalikan nilai asli
def remove_html(text):
if isinstance(text, str):
html = re.compile(r'<.*?>')
return html.sub(r'', text)
return text
def remove_emoji(text):
if isinstance(text, str):
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emotikon wajah
u"\U0001F300-\U0001F5FF" # simbol & gambar
u"\U0001F680-\U0001F6FF" # transportasi & simbol
u"\U0001F1E0-\U0001F1FF" # bendera negara
"]+", flags=re.UNICODE)
return emoji_pattern.sub(r'', text)
return text
def remove_numbers(text):
if isinstance(text, str):
return re.sub(r'\d+', '', text)
return text
def remove_symbols(text):
if isinstance(text, str):
return re.sub(r'[^a-zA-Z0-9\s]', '', text)
return text
tfidf_df = pd.DataFrame(
tfidf_matrix.toarray(),
columns=vectorizer.get_feature_names_out() # Alternatif untuk versi terbaru
)
Menampilkan 10 baris pertama
print(tfidf_df.head(10))
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
kolom yang berisi label target
y = df['Category']
Membagi data menjadi data latih dan uji (80% latih, 20% uji)
X_train, X_test, y_train, y_test = train_test_split(tfidf_matrix, y, test_size=0.2, random_state=42)
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
Menentukan target (y)
y = df['Category'] # Target adalah kategori berita
Pisahkan dataset menjadi set pelatihan dan pengujian
X_train, X_test, y_train, y_test = train_test_split(tfidf_df, y, test_size=0.2, random_state=42)