{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "42801c6a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "workding dir: /Users/inflaton/code/engd/papers/maritime/global-incidents\n", "loading env vars from: /Users/inflaton/code/engd/papers/maritime/global-incidents/.env\n" ] }, { "data": { "text/plain": [ "True" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%load_ext autoreload\n", "%autoreload 2\n", "\n", "import os\n", "import sys\n", "from pathlib import Path\n", "\n", "workding_dir = str(Path.cwd().parent)\n", "os.chdir(workding_dir)\n", "sys.path.append(workding_dir)\n", "print(\"workding dir:\", workding_dir)\n", "\n", "from dotenv import find_dotenv, load_dotenv\n", "\n", "found_dotenv = find_dotenv(\".env\")\n", "\n", "if len(found_dotenv) == 0:\n", " found_dotenv = find_dotenv(\".env.example\")\n", "print(f\"loading env vars from: {found_dotenv}\")\n", "load_dotenv(found_dotenv, override=True)" ] }, { "cell_type": "code", "execution_count": 2, "id": "ddf1e32e-7751-43db-9b5a-22cb08e35c6c", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import nltk\n", "from nltk.corpus import PlaintextCorpusReader\n", "from nltk.corpus import stopwords\n", "from nltk.stem.porter import *\n", "from nltk import pos_tag, word_tokenize\n", "from nltk.stem import WordNetLemmatizer\n", "from nltk.probability import FreqDist\n", "from nltk.tokenize import sent_tokenize\n", "from nltk.tokenize import word_tokenize\n", "import contractions\n", "\n", "import gensim\n", "from gensim import corpora\n", "from gensim import similarities\n", "from gensim import models\n", "from gensim.models import CoherenceModel\n", "\n", "# from wordcloud import WordCloud, ImageColorGenerator\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "import pandas as pd\n", "import re\n", "import os\n", "import glob\n", "import json\n", "\n", "import pickle\n", "from datetime import datetime\n", "import datetime\n", "from newspaper import Article\n", "from gnews import GNews" ] }, { "cell_type": "code", "execution_count": 3, "id": "a9c6ed07-a7d0-4aaa-b571-038919c75e05", "metadata": {}, "outputs": [], "source": [ "# Function to get full news article by headline\n", "def get_news_article(headline):\n", " gnews = GNews()\n", " articles = gnews.get_news(headline)\n", "\n", " if articles:\n", " for article in articles:\n", " # Assuming the headline contains the URL of the news article\n", " try:\n", " article = Article(article[\"url\"])\n", " article.download()\n", " article.parse()\n", " return article.url, article.title, article.text\n", " except Exception as e:\n", " # link cannot be scraped\n", " # print(\"get_news_article - exception:\", e)\n", " return [\n", " f\"cannot scrape the url: {e}\",\n", " \"cannot scrape the title\",\n", " \"cannot scrape the content\",\n", " ]\n", " # No articles found for the given title.\n", " else:\n", " return [\"no url found\", \"no title found\", \"no content found\"]" ] }, { "cell_type": "code", "execution_count": 4, "id": "0acaf899-cd96-4424-b825-c71bf042355a", "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Read the CSV file with news titles\n", "csv_file_path = \"data/cleaned_data.csv\"\n", "df = pd.read_csv(csv_file_path)" ] }, { "cell_type": "code", "execution_count": 5, "id": "465acb47-5f57-4d90-a272-7972d56e002b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(5782, 17)" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.shape" ] }, { "cell_type": "code", "execution_count": 6, "id": "801d892d-3b87-4ecf-805e-3441815d00f1", "metadata": {}, "outputs": [], "source": [ "# drop empty news\n", "df.dropna(subset=[\"Headline\"], inplace=True)" ] }, { "cell_type": "code", "execution_count": 7, "id": "a65a8eaf", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(5780, 17)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.shape" ] }, { "cell_type": "code", "execution_count": 8, "id": "1267bf68-4726-49bf-ae21-9fed09682945", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "70" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df[[\"Year\", \"Headline\", \"Region\"]].duplicated().sum()" ] }, { "cell_type": "code", "execution_count": 9, "id": "51e0f672", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(5710, 17)" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df_uni = df.drop_duplicates(subset=[\"Year\", \"Headline\", \"Region\"], keep=\"first\")\n", "df_uni.shape" ] }, { "cell_type": "code", "execution_count": 10, "id": "f3c35a3c-d852-4285-86bf-3f7db7df78e7", "metadata": { "scrolled": true }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ " 13%|█▎ | 757/5710 [27:31<3:29:09, 2.53s/it] /Users/inflaton/anaconda3/envs/maritime/lib/python3.12/site-packages/dateutil/parser/_parser.py:1207: UnknownTimezoneWarning: tzname PST identified but not understood. Pass `tzinfos` argument in order to correctly return a timezone-aware datetime. In a future version, this will raise an exception.\n", " warnings.warn(\"tzname {tzname} identified but not understood. \"\n", " 28%|██▊ | 1588/5710 [57:29<3:22:58, 2.95s/it] /Users/inflaton/anaconda3/envs/maritime/lib/python3.12/site-packages/dateutil/parser/_parser.py:1207: UnknownTimezoneWarning: tzname PDT identified but not understood. Pass `tzinfos` argument in order to correctly return a timezone-aware datetime. In a future version, this will raise an exception.\n", " warnings.warn(\"tzname {tzname} identified but not understood. \"\n", " 68%|██████▊ | 3862/5710 [2:24:11<1:04:55, 2.11s/it] 06/29/2024 07:38:31 PM - newspaper ignoring lxml node error: Input object is not an XML element: HtmlProcessingInstruction\n", " 70%|██████▉ | 3978/5710 [2:27:39<1:44:23, 3.62s/it]Building prefix dict from /Users/inflaton/anaconda3/envs/maritime/lib/python3.12/site-packages/jieba/dict.txt ...\n", "06/29/2024 07:41:56 PM - Building prefix dict from /Users/inflaton/anaconda3/envs/maritime/lib/python3.12/site-packages/jieba/dict.txt ...\n", "Loading model from cache /var/folders/7x/56svhln929zdh2xhr3mwqg4r0000gn/T/jieba.cache\n", "06/29/2024 07:41:56 PM - Loading model from cache /var/folders/7x/56svhln929zdh2xhr3mwqg4r0000gn/T/jieba.cache\n", "Loading model cost 0.28935670852661133 seconds.\n", "06/29/2024 07:41:56 PM - Loading model cost 0.28935670852661133 seconds.\n", "Prefix dict has been built succesfully.\n", "06/29/2024 07:41:56 PM - Prefix dict has been built succesfully.\n", "100%|██████████| 5710/5710 [3:30:27<00:00, 2.21s/it] " ] }, { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 16min 31s, sys: 3min 20s, total: 19min 51s\n", "Wall time: 3h 30min 27s\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n", ":20: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame.\n", "Try using .loc[row_indexer,col_indexer] = value instead\n", "\n", "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", ":21: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame.\n", "Try using .loc[row_indexer,col_indexer] = value instead\n", "\n", "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", ":22: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame.\n", "Try using .loc[row_indexer,col_indexer] = value instead\n", "\n", "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n" ] } ], "source": [ "%%time\n", "\n", "from tqdm import tqdm\n", "\n", "# Iterate through each row and get the full news article\n", "tes = df_uni\n", "\n", "urls = []\n", "titles = []\n", "contents = []\n", "\n", "for index in tqdm(range(len(tes))):\n", " row = tes.iloc[index]\n", " headline = row[\"Headline\"]\n", "\n", " results = get_news_article(headline)\n", " urls.append(results[0])\n", " titles.append(results[1])\n", " contents.append(results[2])\n", "\n", "# Update the DataFrame with the fetched data\n", "tes[\"url\"] = urls\n", "tes[\"title\"] = titles\n", "tes[\"content\"] = contents" ] }, { "cell_type": "code", "execution_count": 11, "id": "66d98c3b-c1f2-42e6-ae5f-8192c5a91f44", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
idHeadlineDetailsSeverityCategoryRegionDatetimeYearlatlonmaritime_labelfound_portscontains_port_infoif_labeledMonthWeekHeadline_Detailsurltitlecontent
01.0Grasberg Mine- Grasberg mine workers extend st...Media sources indicate that workers at the Gra...ModerateMine Workers StrikeIndonesia28/5/17 17:082017.0-4.05608137.11302False['freeport']1.0False5.021.0Grasberg Mine- Grasberg mine workers extend st...https://news.google.com/rss/articles/CBMiZ2h0d...Freeport Indonesia mine workers extend strike ...By Wilda Asmarini and Susan Taylor\\n\\nJAKARTA/...
12.0Indonesia: Undersea internet cables damaged by...News sources are stating that recent typhoons ...MinorTravel WarningIndonesia4/9/17 14:302017.0NaNNaNFalse['hong kong']1.0False4.014.0Indonesia: Undersea internet cables damaged by...no url foundno title foundno content found
23.0Shanghai port congestion impacts terminals in ...The persisting port congestion at Shanghai’s Y...MinorPort CongestionChina27/4/17 9:162017.029.52000121.33190True['ningbo', 'qingdao', 'shanghai']1.0False4.017.0Shanghai port congestion impacts terminals in ...https://news.google.com/rss/articles/CBMiZmh0d...Bad weather causing delays, congestion at majo...LA-LB ports investing $25 million in charging ...
34.0UPDATE - Indonesia: Explosion at KP Terminal i...Updated local media sources from Jakarta indic...ExtremeBombing, Police OperationsIndonesia24/5/17 15:152017.0-6.22465106.86700True['jakarta']1.0False5.021.0UPDATE - Indonesia: Explosion at KP Terminal i...no url foundno title foundno content found
45.0UPDATE - Indonesia: Police confirm two explosi...According to local police in Jakarta, two expl...ExtremeBombing, Police OperationsIndonesia24/5/17 16:202017.0NaNNaNTrue['jakarta']1.0True5.021.0UPDATE - Indonesia: Police confirm two explosi...https://news.google.com/rss/articles/CBMiV2h0d...Three dead confirmed in Jakarta double bombingTwo explosions strike bus station in Indonesia...
...............................................................
57775776.0Winter storm may bring inclement weather condi...Intelligence received by Everstream Analytics ...ModerateIce StormUnited States16/12/20 2:472020.038.90072-77.05440False['new york']1.0False12.051.0Winter storm may bring inclement weather condi...https://news.google.com/rss/articles/CBMiWWh0d...Winter Storm Warnings posted for parts of Nort...A coastal storm is set to deliver another slop...
57785777.0Winter weather expected to continue to impact ...Meteorological sources indicate that a series ...MinorRoadway Closure / Disruption, Ground Transport...United States31/12/20 18:152020.041.30357-72.90561False['new york', 'virginia']1.0True12.053.0Winter weather expected to continue to impact ...https://news.google.com/rss/articles/CBMiT2h0d...Deadly nor'easter wreaks havoc in New England ...BOSTON – A deadly late-season nor’easter that ...
57795778.0Workers of Svitzer Australia plan to strike on...Industry sources report on December 7 that Svi...ModerateIndustrial ActionAustralia7/12/20 6:162020.0-38.35169145.25050False['geelong', 'melbourne']1.0False7.028.0Workers of Svitzer Australia plan to strike on...no url foundno title foundno content found
57805779.0Workers stage 24-hour stoppage at DP World Ter...Industry sources indicate on December 14 that ...ModeratePort StrikeAustralia14/12/20 16:522020.0NaNNaNTrue['fremantle']1.0True12.051.0Workers stage 24-hour stoppage at DP World Ter...https://news.google.com/rss/articles/CBMiOWh0d...Union shuts down strikes as DP World threatens...The Maritime Union of Australia (MUA) has curt...
57815780.0Workers with Ertsoverslagbedrijf Europoort C.V...On November 17, Dutch media sources reported t...MinorPort StrikeNetherlands18/11/20 17:552020.051.961214.10550False['rotterdam']1.0True11.047.0Workers with Ertsoverslagbedrijf Europoort C.V...no url foundno title foundno content found
\n", "

5710 rows × 20 columns

\n", "
" ], "text/plain": [ " id Headline \\\n", "0 1.0 Grasberg Mine- Grasberg mine workers extend st... \n", "1 2.0 Indonesia: Undersea internet cables damaged by... \n", "2 3.0 Shanghai port congestion impacts terminals in ... \n", "3 4.0 UPDATE - Indonesia: Explosion at KP Terminal i... \n", "4 5.0 UPDATE - Indonesia: Police confirm two explosi... \n", "... ... ... \n", "5777 5776.0 Winter storm may bring inclement weather condi... \n", "5778 5777.0 Winter weather expected to continue to impact ... \n", "5779 5778.0 Workers of Svitzer Australia plan to strike on... \n", "5780 5779.0 Workers stage 24-hour stoppage at DP World Ter... \n", "5781 5780.0 Workers with Ertsoverslagbedrijf Europoort C.V... \n", "\n", " Details Severity \\\n", "0 Media sources indicate that workers at the Gra... Moderate \n", "1 News sources are stating that recent typhoons ... Minor \n", "2 The persisting port congestion at Shanghai’s Y... Minor \n", "3 Updated local media sources from Jakarta indic... Extreme \n", "4 According to local police in Jakarta, two expl... Extreme \n", "... ... ... \n", "5777 Intelligence received by Everstream Analytics ... Moderate \n", "5778 Meteorological sources indicate that a series ... Minor \n", "5779 Industry sources report on December 7 that Svi... Moderate \n", "5780 Industry sources indicate on December 14 that ... Moderate \n", "5781 On November 17, Dutch media sources reported t... Minor \n", "\n", " Category Region \\\n", "0 Mine Workers Strike Indonesia \n", "1 Travel Warning Indonesia \n", "2 Port Congestion China \n", "3 Bombing, Police Operations Indonesia \n", "4 Bombing, Police Operations Indonesia \n", "... ... ... \n", "5777 Ice Storm United States \n", "5778 Roadway Closure / Disruption, Ground Transport... United States \n", "5779 Industrial Action Australia \n", "5780 Port Strike Australia \n", "5781 Port Strike Netherlands \n", "\n", " Datetime Year lat lon maritime_label \\\n", "0 28/5/17 17:08 2017.0 -4.05608 137.11302 False \n", "1 4/9/17 14:30 2017.0 NaN NaN False \n", "2 27/4/17 9:16 2017.0 29.52000 121.33190 True \n", "3 24/5/17 15:15 2017.0 -6.22465 106.86700 True \n", "4 24/5/17 16:20 2017.0 NaN NaN True \n", "... ... ... ... ... ... \n", "5777 16/12/20 2:47 2020.0 38.90072 -77.05440 False \n", "5778 31/12/20 18:15 2020.0 41.30357 -72.90561 False \n", "5779 7/12/20 6:16 2020.0 -38.35169 145.25050 False \n", "5780 14/12/20 16:52 2020.0 NaN NaN True \n", "5781 18/11/20 17:55 2020.0 51.96121 4.10550 False \n", "\n", " found_ports contains_port_info if_labeled Month \\\n", "0 ['freeport'] 1.0 False 5.0 \n", "1 ['hong kong'] 1.0 False 4.0 \n", "2 ['ningbo', 'qingdao', 'shanghai'] 1.0 False 4.0 \n", "3 ['jakarta'] 1.0 False 5.0 \n", "4 ['jakarta'] 1.0 True 5.0 \n", "... ... ... ... ... \n", "5777 ['new york'] 1.0 False 12.0 \n", "5778 ['new york', 'virginia'] 1.0 True 12.0 \n", "5779 ['geelong', 'melbourne'] 1.0 False 7.0 \n", "5780 ['fremantle'] 1.0 True 12.0 \n", "5781 ['rotterdam'] 1.0 True 11.0 \n", "\n", " Week Headline_Details \\\n", "0 21.0 Grasberg Mine- Grasberg mine workers extend st... \n", "1 14.0 Indonesia: Undersea internet cables damaged by... \n", "2 17.0 Shanghai port congestion impacts terminals in ... \n", "3 21.0 UPDATE - Indonesia: Explosion at KP Terminal i... \n", "4 21.0 UPDATE - Indonesia: Police confirm two explosi... \n", "... ... ... \n", "5777 51.0 Winter storm may bring inclement weather condi... \n", "5778 53.0 Winter weather expected to continue to impact ... \n", "5779 28.0 Workers of Svitzer Australia plan to strike on... \n", "5780 51.0 Workers stage 24-hour stoppage at DP World Ter... \n", "5781 47.0 Workers with Ertsoverslagbedrijf Europoort C.V... \n", "\n", " url \\\n", "0 https://news.google.com/rss/articles/CBMiZ2h0d... \n", "1 no url found \n", "2 https://news.google.com/rss/articles/CBMiZmh0d... \n", "3 no url found \n", "4 https://news.google.com/rss/articles/CBMiV2h0d... \n", "... ... \n", "5777 https://news.google.com/rss/articles/CBMiWWh0d... \n", "5778 https://news.google.com/rss/articles/CBMiT2h0d... \n", "5779 no url found \n", "5780 https://news.google.com/rss/articles/CBMiOWh0d... \n", "5781 no url found \n", "\n", " title \\\n", "0 Freeport Indonesia mine workers extend strike ... \n", "1 no title found \n", "2 Bad weather causing delays, congestion at majo... \n", "3 no title found \n", "4 Three dead confirmed in Jakarta double bombing \n", "... ... \n", "5777 Winter Storm Warnings posted for parts of Nort... \n", "5778 Deadly nor'easter wreaks havoc in New England ... \n", "5779 no title found \n", "5780 Union shuts down strikes as DP World threatens... \n", "5781 no title found \n", "\n", " content \n", "0 By Wilda Asmarini and Susan Taylor\\n\\nJAKARTA/... \n", "1 no content found \n", "2 LA-LB ports investing $25 million in charging ... \n", "3 no content found \n", "4 Two explosions strike bus station in Indonesia... \n", "... ... \n", "5777 A coastal storm is set to deliver another slop... \n", "5778 BOSTON – A deadly late-season nor’easter that ... \n", "5779 no content found \n", "5780 The Maritime Union of Australia (MUA) has curt... \n", "5781 no content found \n", "\n", "[5710 rows x 20 columns]" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tes" ] }, { "cell_type": "code", "execution_count": 12, "id": "d6fe260c-1bbb-4556-b9ac-2b9b62c5ba5f", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3218" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "count_rows = tes[\n", " ~tes[\"content\"].isin([\"cannot scrape the content\", \"no content found\"])\n", "].shape[0]\n", "count_rows" ] }, { "cell_type": "code", "execution_count": 13, "id": "6818fe7b-6e7d-4d30-8ee8-866b29fd40c8", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2132" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "count_rows = tes[tes[\"content\"].isin([\"no content found\"])].shape[0]\n", "count_rows" ] }, { "cell_type": "code", "execution_count": 14, "id": "f59e2ce4-072a-43e2-a247-fd399c388c2d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "360" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "count_rows = tes[tes[\"content\"].isin([\"cannot scrape the content\"])].shape[0]\n", "count_rows" ] }, { "cell_type": "code", "execution_count": 15, "id": "8063b964", "metadata": {}, "outputs": [], "source": [ "scrapped_df1 = pd.read_parquet(\"data/scrapped_data1.parquet\")" ] }, { "cell_type": "code", "execution_count": 16, "id": "78896dd3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(5710, 20)" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "scrapped_df1.shape" ] }, { "cell_type": "code", "execution_count": 17, "id": "316d6be5", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 5710/5710 [00:00<00:00, 35312.10it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 162 ms, sys: 3.81 ms, total: 166 ms\n", "Wall time: 165 ms\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n", ":23: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame.\n", "Try using .loc[row_indexer,col_indexer] = value instead\n", "\n", "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", ":24: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame.\n", "Try using .loc[row_indexer,col_indexer] = value instead\n", "\n", "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", ":25: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame.\n", "Try using .loc[row_indexer,col_indexer] = value instead\n", "\n", "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n" ] } ], "source": [ "%%time\n", "\n", "from tqdm import tqdm\n", "\n", "urls = []\n", "titles = []\n", "contents = []\n", "\n", "not_found = [\"cannot scrape the content\", \"no content found\", None]\n", "\n", "for index in tqdm(range(len(tes))):\n", " row1 = scrapped_df1.iloc[index]\n", " row2 = tes.iloc[index]\n", " \n", " if row1[\"content\"] in not_found and not row2[\"content\"] in not_found and row2[\"title\"] is not None:\n", " row = row2\n", " else:\n", " row = row1\n", "\n", " urls.append(row[\"url\"])\n", " titles.append(row[\"title\"])\n", " contents.append(row[\"content\"])\n", "\n", "# Update the DataFrame with the fetched data\n", "tes[\"url\"] = urls\n", "tes[\"title\"] = titles\n", "tes[\"content\"] = contents" ] }, { "cell_type": "code", "execution_count": 18, "id": "4926f410", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3694" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "count_rows = tes[~tes[\"content\"].isin(not_found)].shape[0]\n", "count_rows" ] }, { "cell_type": "code", "execution_count": 19, "id": "44bff271", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.6469352014010508" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "count_rows / len(tes)" ] }, { "cell_type": "code", "execution_count": 20, "id": "e573b48a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1945" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "count_rows = tes[tes[\"content\"].isin([\"no content found\"])].shape[0]\n", "count_rows" ] }, { "cell_type": "code", "execution_count": 21, "id": "d4a527b3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "71" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "count_rows = tes[tes[\"content\"].isin([\"cannot scrape the content\"])].shape[0]\n", "count_rows" ] }, { "cell_type": "code", "execution_count": 22, "id": "158acaec", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/var/folders/7x/56svhln929zdh2xhr3mwqg4r0000gn/T/ipykernel_64033/1183224327.py:1: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame.\n", "Try using .loc[row_indexer,col_indexer] = value instead\n", "\n", "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", " tes[\"id\"] = tes[\"id\"].astype(int)\n" ] } ], "source": [ "tes[\"id\"] = tes[\"id\"].astype(int)" ] }, { "cell_type": "code", "execution_count": 23, "id": "154aada9-8e4a-479a-8288-a63b72ae86ad", "metadata": {}, "outputs": [], "source": [ "tes.to_csv(\"data/scrapped_data2.csv\", index=False)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.4" } }, "nbformat": 4, "nbformat_minor": 5 }