├── README.md ├── .gitignore ├── tutorials ├── 01_Introduction to NLP │ ├── 01_Introduction_to_NLP_Parts_of_Speech_Tagging.ipynb │ ├── 02_Introduction_to_NLP_Named_Entity_Recognition.ipynb │ └── 00_Introduction_to_NLP_Basics.ipynb └── 03_NLP Applications │ └── 10_NLP_Applications_Text_Classification_Deep_Learning_CNN_Models.ipynb └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # Practical Natural Language Processing with Python Workshop 2 | 3 | With a hands-on and interactive approach, we will understand essential concepts in NLP along with extensive case- studies and hands-on examples to master state-of-the-art tools, techniques and frameworks for actually applying NLP to solve real- world problems. We will leverage machine learning, deep learning and deep transfer learning to solve some popular tasks in NLP. 4 | 5 | We will leverage machine learning, deep learning and deep transfer learning to solve some popular tasks in NLP including the following: 6 | 7 | - Introduction to NLP 8 | - Basics 9 | - POS Tagging 10 | - NER 11 | - Text Wrangling 12 | 13 | - Text Representation 14 | - Traditional Statistical Models – BOW, TFIDF 15 | - Embedding Models 16 | 17 | - NLP Applications 18 | - Text Similarity Content Recommenders 19 | - Topic Modeling 20 | - Text Summarization (Extractive) 21 | - Text Classification (ML, DNN, CNN, LSTM, BERT) 22 | - Multi-Task NLP (Transformers) 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /tutorials/01_Introduction to NLP/01_Introduction_to_NLP_Parts_of_Speech_Tagging.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "01_Introduction_to_NLP_Parts_of_Speech_Tagging.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "display_name": "Python 3", 12 | "language": "python", 13 | "name": "python3" 14 | }, 15 | "language_info": { 16 | "codemirror_mode": { 17 | "name": "ipython", 18 | "version": 3 19 | }, 20 | "file_extension": ".py", 21 | "mimetype": "text/x-python", 22 | "name": "python", 23 | "nbconvert_exporter": "python", 24 | "pygments_lexer": "ipython3", 25 | "version": "3.7.6" 26 | } 27 | }, 28 | "cells": [ 29 | { 30 | "cell_type": "markdown", 31 | "metadata": { 32 | "id": "mezUX-HyVI0x" 33 | }, 34 | "source": [ 35 | "# Parts of Speech Tagging\n", 36 | "\n", 37 | "Source: https://towardsdatascience.com/a-practitioners-guide-to-natural-language-processing-part-i-processing-understanding-text-9f4abfd13e72\n", 38 | "\n", 39 | "For any language, syntax and structure usually go hand in hand, where a set of specific rules, conventions, and principles govern the way words are combined into phrases; phrases get combines into clauses; and clauses get combined into sentences. \n", 40 | "\n", 41 | "Knowledge about the structure and syntax of language is helpful in many areas like text processing, annotation, and parsing for further operations such as text classification or summarization.\n", 42 | "\n", 43 | "__Parts of speech (POS)__ are specific lexical categories to which words are assigned, based on their syntactic context and role. Usually, words can fall into one of the following major categories.\n", 44 | "\n", 45 | "+ __N(oun)__: This usually denotes words that depict some object or entity, which may be living or nonliving. Some examples would be fox , dog , book , and so on. The POS tag symbol for nouns is N.\n", 46 | "\n", 47 | "+ __V(erb)__: Verbs are words that are used to describe certain actions, states, or occurrences. There are a wide variety of further subcategories, such as auxiliary, reflexive, and transitive verbs (and many more). Some typical examples of verbs would be running , jumping , read , and write . The POS tag symbol for verbs is V.\n", 48 | "\n", 49 | "+ __Adj(ective)__: Adjectives are words used to describe or qualify other words, typically nouns and noun phrases. The phrase beautiful flower has the noun (N) flower which is described or qualified using the adjective (ADJ) beautiful . The POS tag symbol for adjectives is ADJ .\n", 50 | "\n", 51 | "+ __Adv(erb)__: Adverbs usually act as modifiers for other words including nouns, adjectives, verbs, or other adverbs. The phrase very beautiful flower has the adverb (ADV) very , which modifies the adjective (ADJ) beautiful , indicating the degree to which the flower is beautiful. The POS tag symbol for adverbs is ADV.\n", 52 | "\n", 53 | "Besides these four major categories of parts of speech , there are other categories that occur frequently in the English language. These include pronouns, prepositions, interjections, conjunctions, determiners, and many others. Furthermore, each POS tag like the noun (N) can be further subdivided into categories like __singular nouns (NN)__, __singular proper nouns (NNP)__, and __plural nouns (NNS)__.\n", 54 | "\n", 55 | "The process of classifying and labeling POS tags for words called parts of speech tagging or POS tagging . " 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "metadata": { 61 | "colab": { 62 | "base_uri": "https://localhost:8080/", 63 | "height": 35 64 | }, 65 | "id": "hvix96uIVI0x", 66 | "outputId": "4c78d9a5-f214-420e-dfc0-7d9f347936d2" 67 | }, 68 | "source": [ 69 | "sentence = 'This NLP Workshop is being organized as a part of the GIDS AI/ML & DATA Live Conference 2020'\n", 70 | "sentence" 71 | ], 72 | "execution_count": 1, 73 | "outputs": [ 74 | { 75 | "output_type": "execute_result", 76 | "data": { 77 | "application/vnd.google.colaboratory.intrinsic+json": { 78 | "type": "string" 79 | }, 80 | "text/plain": [ 81 | "'This NLP Workshop is being organized as a part of the GIDS AI/ML & DATA Live Conference 2020'" 82 | ] 83 | }, 84 | "metadata": { 85 | "tags": [] 86 | }, 87 | "execution_count": 1 88 | } 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "metadata": { 94 | "colab": { 95 | "base_uri": "https://localhost:8080/" 96 | }, 97 | "id": "7j9ElOtMVI01", 98 | "outputId": "39c7ebdf-2de0-4397-9312-623b8947fae2" 99 | }, 100 | "source": [ 101 | "import nltk\n", 102 | "nltk.download('punkt')\n", 103 | "nltk.download('averaged_perceptron_tagger')" 104 | ], 105 | "execution_count": 2, 106 | "outputs": [ 107 | { 108 | "output_type": "stream", 109 | "text": [ 110 | "[nltk_data] Downloading package punkt to /root/nltk_data...\n", 111 | "[nltk_data] Unzipping tokenizers/punkt.zip.\n", 112 | "[nltk_data] Downloading package averaged_perceptron_tagger to\n", 113 | "[nltk_data] /root/nltk_data...\n", 114 | "[nltk_data] Unzipping taggers/averaged_perceptron_tagger.zip.\n" 115 | ], 116 | "name": "stdout" 117 | }, 118 | { 119 | "output_type": "execute_result", 120 | "data": { 121 | "text/plain": [ 122 | "True" 123 | ] 124 | }, 125 | "metadata": { 126 | "tags": [] 127 | }, 128 | "execution_count": 2 129 | } 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "metadata": { 135 | "colab": { 136 | "base_uri": "https://localhost:8080/" 137 | }, 138 | "id": "z6V2Ek6-VkpT", 139 | "outputId": "c5ce40db-a18d-4697-d890-93e9443039a0" 140 | }, 141 | "source": [ 142 | "nltk_pos_tagged = nltk.pos_tag(nltk.word_tokenize(sentence))\n", 143 | "nltk_pos_tagged" 144 | ], 145 | "execution_count": 3, 146 | "outputs": [ 147 | { 148 | "output_type": "execute_result", 149 | "data": { 150 | "text/plain": [ 151 | "[('This', 'DT'),\n", 152 | " ('NLP', 'NNP'),\n", 153 | " ('Workshop', 'NNP'),\n", 154 | " ('is', 'VBZ'),\n", 155 | " ('being', 'VBG'),\n", 156 | " ('organized', 'VBN'),\n", 157 | " ('as', 'IN'),\n", 158 | " ('a', 'DT'),\n", 159 | " ('part', 'NN'),\n", 160 | " ('of', 'IN'),\n", 161 | " ('the', 'DT'),\n", 162 | " ('GIDS', 'NNP'),\n", 163 | " ('AI/ML', 'NNP'),\n", 164 | " ('&', 'CC'),\n", 165 | " ('DATA', 'NNP'),\n", 166 | " ('Live', 'NNP'),\n", 167 | " ('Conference', 'NNP'),\n", 168 | " ('2020', 'CD')]" 169 | ] 170 | }, 171 | "metadata": { 172 | "tags": [] 173 | }, 174 | "execution_count": 3 175 | } 176 | ] 177 | }, 178 | { 179 | "cell_type": "code", 180 | "metadata": { 181 | "colab": { 182 | "base_uri": "https://localhost:8080/", 183 | "height": 106 184 | }, 185 | "id": "ctmJlb-tVI03", 186 | "outputId": "24a32529-9f9e-4195-df82-53c72192bc90" 187 | }, 188 | "source": [ 189 | "import pandas as pd\n", 190 | "\n", 191 | "pd.DataFrame(nltk_pos_tagged, \n", 192 | " columns=['Word', 'POS tag']).T" 193 | ], 194 | "execution_count": 4, 195 | "outputs": [ 196 | { 197 | "output_type": "execute_result", 198 | "data": { 199 | "text/html": [ 200 | "
\n", 201 | "\n", 214 | "\n", 215 | " \n", 216 | " \n", 217 | " \n", 218 | " \n", 219 | " \n", 220 | " \n", 221 | " \n", 222 | " \n", 223 | " \n", 224 | " \n", 225 | " \n", 226 | " \n", 227 | " \n", 228 | " \n", 229 | " \n", 230 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | " \n", 244 | " \n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " \n", 249 | " \n", 250 | " \n", 251 | " \n", 252 | " \n", 253 | " \n", 254 | " \n", 255 | " \n", 256 | " \n", 257 | " \n", 258 | " \n", 259 | " \n", 260 | " \n", 261 | " \n", 262 | " \n", 263 | " \n", 264 | " \n", 265 | " \n", 266 | " \n", 267 | " \n", 268 | " \n", 269 | " \n", 270 | " \n", 271 | " \n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | " \n", 276 | " \n", 277 | " \n", 278 | " \n", 279 | " \n", 280 | " \n", 281 | " \n", 282 | "
01234567891011121314151617
WordThisNLPWorkshopisbeingorganizedasapartoftheGIDSAI/ML&DATALiveConference2020
POS tagDTNNPNNPVBZVBGVBNINDTNNINDTNNPNNPCCNNPNNPNNPCD
\n", 283 | "
" 284 | ], 285 | "text/plain": [ 286 | " 0 1 2 3 4 ... 13 14 15 16 17\n", 287 | "Word This NLP Workshop is being ... & DATA Live Conference 2020\n", 288 | "POS tag DT NNP NNP VBZ VBG ... CC NNP NNP NNP CD\n", 289 | "\n", 290 | "[2 rows x 18 columns]" 291 | ] 292 | }, 293 | "metadata": { 294 | "tags": [] 295 | }, 296 | "execution_count": 4 297 | } 298 | ] 299 | }, 300 | { 301 | "cell_type": "code", 302 | "metadata": { 303 | "id": "EcTCrMhoVI06" 304 | }, 305 | "source": [ 306 | "import spacy\n", 307 | "\n", 308 | "nlp = spacy.load('en')" 309 | ], 310 | "execution_count": 5, 311 | "outputs": [] 312 | }, 313 | { 314 | "cell_type": "code", 315 | "metadata": { 316 | "colab": { 317 | "base_uri": "https://localhost:8080/" 318 | }, 319 | "id": "tOO_jetwVI08", 320 | "outputId": "0ca17631-9909-4632-d7e6-1ac485a84b4f" 321 | }, 322 | "source": [ 323 | "sentence_nlp = nlp(sentence)\n", 324 | "spacy_pos_tagged = [(word, word.tag_, word.pos_) for word in sentence_nlp]\n", 325 | "spacy_pos_tagged" 326 | ], 327 | "execution_count": 6, 328 | "outputs": [ 329 | { 330 | "output_type": "execute_result", 331 | "data": { 332 | "text/plain": [ 333 | "[(This, 'DT', 'DET'),\n", 334 | " (NLP, 'NNP', 'PROPN'),\n", 335 | " (Workshop, 'NNP', 'PROPN'),\n", 336 | " (is, 'VBZ', 'AUX'),\n", 337 | " (being, 'VBG', 'AUX'),\n", 338 | " (organized, 'VBN', 'VERB'),\n", 339 | " (as, 'IN', 'SCONJ'),\n", 340 | " (a, 'DT', 'DET'),\n", 341 | " (part, 'NN', 'NOUN'),\n", 342 | " (of, 'IN', 'ADP'),\n", 343 | " (the, 'DT', 'DET'),\n", 344 | " (GIDS, 'NNP', 'PROPN'),\n", 345 | " (AI, 'NNP', 'PROPN'),\n", 346 | " (/, 'SYM', 'SYM'),\n", 347 | " (ML, 'NNP', 'PROPN'),\n", 348 | " (&, 'CC', 'CCONJ'),\n", 349 | " (DATA, 'NNP', 'PROPN'),\n", 350 | " (Live, 'NNP', 'PROPN'),\n", 351 | " (Conference, 'NNP', 'PROPN'),\n", 352 | " (2020, 'CD', 'NUM')]" 353 | ] 354 | }, 355 | "metadata": { 356 | "tags": [] 357 | }, 358 | "execution_count": 6 359 | } 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "metadata": { 365 | "colab": { 366 | "base_uri": "https://localhost:8080/", 367 | "height": 136 368 | }, 369 | "id": "w_AYcByRVI0-", 370 | "outputId": "cf6e696e-ac40-457e-a251-fd5dd1746a3e" 371 | }, 372 | "source": [ 373 | "pd.DataFrame(spacy_pos_tagged, \n", 374 | " columns=['Word', 'POS tag', 'Tag type']).T" 375 | ], 376 | "execution_count": 7, 377 | "outputs": [ 378 | { 379 | "output_type": "execute_result", 380 | "data": { 381 | "text/html": [ 382 | "
\n", 383 | "\n", 396 | "\n", 397 | " \n", 398 | " \n", 399 | " \n", 400 | " \n", 401 | " \n", 402 | " \n", 403 | " \n", 404 | " \n", 405 | " \n", 406 | " \n", 407 | " \n", 408 | " \n", 409 | " \n", 410 | " \n", 411 | " \n", 412 | " \n", 413 | " \n", 414 | " \n", 415 | " \n", 416 | " \n", 417 | " \n", 418 | " \n", 419 | " \n", 420 | " \n", 421 | " \n", 422 | " \n", 423 | " \n", 424 | " \n", 425 | " \n", 426 | " \n", 427 | " \n", 428 | " \n", 429 | " \n", 430 | " \n", 431 | " \n", 432 | " \n", 433 | " \n", 434 | " \n", 435 | " \n", 436 | " \n", 437 | " \n", 438 | " \n", 439 | " \n", 440 | " \n", 441 | " \n", 442 | " \n", 443 | " \n", 444 | " \n", 445 | " \n", 446 | " \n", 447 | " \n", 448 | " \n", 449 | " \n", 450 | " \n", 451 | " \n", 452 | " \n", 453 | " \n", 454 | " \n", 455 | " \n", 456 | " \n", 457 | " \n", 458 | " \n", 459 | " \n", 460 | " \n", 461 | " \n", 462 | " \n", 463 | " \n", 464 | " \n", 465 | " \n", 466 | " \n", 467 | " \n", 468 | " \n", 469 | " \n", 470 | " \n", 471 | " \n", 472 | " \n", 473 | " \n", 474 | " \n", 475 | " \n", 476 | " \n", 477 | " \n", 478 | " \n", 479 | " \n", 480 | " \n", 481 | " \n", 482 | " \n", 483 | " \n", 484 | " \n", 485 | " \n", 486 | " \n", 487 | " \n", 488 | " \n", 489 | " \n", 490 | " \n", 491 | " \n", 492 | " \n", 493 | "
012345678910111213141516171819
WordThisNLPWorkshopisbeingorganizedasapartoftheGIDSAI/ML&DATALiveConference2020
POS tagDTNNPNNPVBZVBGVBNINDTNNINDTNNPNNPSYMNNPCCNNPNNPNNPCD
Tag typeDETPROPNPROPNAUXAUXVERBSCONJDETNOUNADPDETPROPNPROPNSYMPROPNCCONJPROPNPROPNPROPNNUM
\n", 494 | "
" 495 | ], 496 | "text/plain": [ 497 | " 0 1 2 3 ... 16 17 18 19\n", 498 | "Word This NLP Workshop is ... DATA Live Conference 2020\n", 499 | "POS tag DT NNP NNP VBZ ... NNP NNP NNP CD\n", 500 | "Tag type DET PROPN PROPN AUX ... PROPN PROPN PROPN NUM\n", 501 | "\n", 502 | "[3 rows x 20 columns]" 503 | ] 504 | }, 505 | "metadata": { 506 | "tags": [] 507 | }, 508 | "execution_count": 7 509 | } 510 | ] 511 | }, 512 | { 513 | "cell_type": "markdown", 514 | "metadata": { 515 | "id": "vucQ8o8OVI1A" 516 | }, 517 | "source": [ 518 | "## Guide to POS Tags\n", 519 | "\n", 520 | "The most common part of speech (POS) tag schemes are those developed for the Penn Treebank.\n", 521 | "\n", 522 | "| POS Tag | Description | Example |\n", 523 | "|---------|---------------------------------------|-----------------------------------------|\n", 524 | "| CC | coordinating conjunction | and |\n", 525 | "| CD | cardinal number | 1, third |\n", 526 | "| DT | determiner | the |\n", 527 | "| EX | existential there | there is |\n", 528 | "| FW | foreign word | d’hoevre |\n", 529 | "| IN | preposition/subordinating conjunction | in, of, like |\n", 530 | "| JJ | adjective | big |\n", 531 | "| JJR | adjective, comparative | bigger |\n", 532 | "| JJS | adjective, superlative | biggest |\n", 533 | "| LS | list marker | 1) |\n", 534 | "| MD | modal | could, will |\n", 535 | "| NN | noun, singular or mass | door |\n", 536 | "| NNS | noun plural | doors |\n", 537 | "| NNP | proper noun, singular | John |\n", 538 | "| NNPS | proper noun, plural | Vikings |\n", 539 | "| PDT | predeterminer | both the boys |\n", 540 | "| POS | possessive ending | friend‘s |\n", 541 | "| PRP | personal pronoun | I, he, it |\n", 542 | "| PRP\\$ | possessive pronoun | my, his |\n", 543 | "| RB | adverb | however, usually, naturally, here, good |\n", 544 | "| RBR | adverb, comparative | better |\n", 545 | "| RBS | adverb, superlative | best |\n", 546 | "| RP | particle | give up |\n", 547 | "| TO | to | to go, to him |\n", 548 | "| UH | interjection | uhhuhhuhh |\n", 549 | "| VB | verb, base form | take |\n", 550 | "| VBD | verb, past tense | took |\n", 551 | "| VBG | verb, gerund/present participle | taking |\n", 552 | "| VBN | verb, past participle | taken |\n", 553 | "| VBP | verb, sing. present, non-3d | take |\n", 554 | "| VBZ | verb, 3rd person sing. present | takes |\n", 555 | "| WDT | wh-determiner | which |\n", 556 | "| WP | wh-pronoun | who, what |\n", 557 | "| WP\\$ | possessive wh-pronoun | whose |\n", 558 | "| WRB | wh-abverb | where, when |\n", 559 | "\n", 560 | "Source: https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html" 561 | ] 562 | } 563 | ] 564 | } -------------------------------------------------------------------------------- /tutorials/01_Introduction to NLP/02_Introduction_to_NLP_Named_Entity_Recognition.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "colab_type": "text", 7 | "id": "UqtCNDFVWkv-" 8 | }, 9 | "source": [ 10 | "# Named Entity Recognition\n", 11 | "\n", 12 | "In any text document, there are particular terms that represent specific entities that are more informative and have a unique context. These entities are known as named entities , which more specifically refer to terms that represent real-world objects like people, places, organizations, and so on, which are often denoted by proper names. \n", 13 | "\n", 14 | "__Named entity recognition (NER)__ , also known as entity chunking/extraction , is a popular technique used in information extraction to identify and segment the named entities and classify or categorize them under various predefined classes.\n", 15 | "\n", 16 | "There are out of the box NER taggers available through popular libraries like __`nltk`__ and __`spacy`__. Each library follows a different approach to solve the problem." 17 | ] 18 | }, 19 | { 20 | "cell_type": "markdown", 21 | "metadata": { 22 | "colab_type": "text", 23 | "id": "f0vWGV-xWkv_" 24 | }, 25 | "source": [ 26 | "# NER with SpaCy" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 1, 32 | "metadata": { 33 | "colab": { 34 | "base_uri": "https://localhost:8080/", 35 | "height": 185 36 | }, 37 | "colab_type": "code", 38 | "id": "_dRV4z_HWkwA", 39 | "outputId": "c6064625-ecd1-49d9-ee09-cc86da389d8d" 40 | }, 41 | "outputs": [ 42 | { 43 | "name": "stdout", 44 | "output_type": "stream", 45 | "text": [ 46 | "Three more countries have joined an “international grand committee” of parliaments, adding to calls for \n", 47 | "Facebook’s boss, Mark Zuckerberg, to give evidence on misinformation to the coalition. Brazil, Latvia and Singapore \n", 48 | "bring the total to eight different parliaments across the world, with plans to send representatives to London on 27 \n", 49 | "November with the intention of hearing from Zuckerberg. Since the Cambridge Analytica scandal broke, the Facebook chief \n", 50 | "has only appeared in front of two legislatures: the American Senate and House of Representatives, and the European parliament. \n", 51 | "Facebook has consistently rebuffed attempts from others, including the UK and Canadian parliaments, to hear from Zuckerberg. \n", 52 | "He added that an article in the New York Times on Thursday, in which the paper alleged a pattern of behaviour from Facebook \n", 53 | "to “delay, deny and deflect” negative news stories, “raises further questions about how recent data breaches were allegedly \n", 54 | "dealt with within Facebook.”\n", 55 | "\n" 56 | ] 57 | } 58 | ], 59 | "source": [ 60 | "text = \"\"\"Three more countries have joined an “international grand committee” of parliaments, adding to calls for \n", 61 | "Facebook’s boss, Mark Zuckerberg, to give evidence on misinformation to the coalition. Brazil, Latvia and Singapore \n", 62 | "bring the total to eight different parliaments across the world, with plans to send representatives to London on 27 \n", 63 | "November with the intention of hearing from Zuckerberg. Since the Cambridge Analytica scandal broke, the Facebook chief \n", 64 | "has only appeared in front of two legislatures: the American Senate and House of Representatives, and the European parliament. \n", 65 | "Facebook has consistently rebuffed attempts from others, including the UK and Canadian parliaments, to hear from Zuckerberg. \n", 66 | "He added that an article in the New York Times on Thursday, in which the paper alleged a pattern of behaviour from Facebook \n", 67 | "to “delay, deny and deflect” negative news stories, “raises further questions about how recent data breaches were allegedly \n", 68 | "dealt with within Facebook.”\n", 69 | "\"\"\"\n", 70 | "print(text)" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": 2, 76 | "metadata": { 77 | "colab": { 78 | "base_uri": "https://localhost:8080/", 79 | "height": 54 80 | }, 81 | "colab_type": "code", 82 | "id": "b8e6nHP9WkwC", 83 | "outputId": "3f3a6197-32a1-4b20-8bff-5155f6428e04" 84 | }, 85 | "outputs": [ 86 | { 87 | "data": { 88 | "text/plain": [ 89 | "'Three more countries have joined an “international grand committee” of parliaments, adding to calls for Facebook’s boss, Mark Zuckerberg, to give evidence on misinformation to the coalition. Brazil, Latvia and Singapore bring the total to eight different parliaments across the world, with plans to send representatives to London on 27 November with the intention of hearing from Zuckerberg. Since the Cambridge Analytica scandal broke, the Facebook chief has only appeared in front of two legislatures: the American Senate and House of Representatives, and the European parliament. Facebook has consistently rebuffed attempts from others, including the UK and Canadian parliaments, to hear from Zuckerberg. He added that an article in the New York Times on Thursday, in which the paper alleged a pattern of behaviour from Facebook to “delay, deny and deflect” negative news stories, “raises further questions about how recent data breaches were allegedly dealt with within Facebook.”'" 90 | ] 91 | }, 92 | "execution_count": 2, 93 | "metadata": { 94 | "tags": [] 95 | }, 96 | "output_type": "execute_result" 97 | } 98 | ], 99 | "source": [ 100 | "import re\n", 101 | "\n", 102 | "text = re.sub(r'\\n', '', text)\n", 103 | "text" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": 0, 109 | "metadata": { 110 | "colab": {}, 111 | "colab_type": "code", 112 | "id": "5wRsBny_WkwE" 113 | }, 114 | "outputs": [], 115 | "source": [ 116 | "import spacy\n", 117 | "\n", 118 | "nlp = spacy.load('en')\n", 119 | "text_nlp = nlp(text)" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": 4, 125 | "metadata": { 126 | "colab": { 127 | "base_uri": "https://localhost:8080/", 128 | "height": 54 129 | }, 130 | "colab_type": "code", 131 | "id": "V-qBRZOcWkwH", 132 | "outputId": "1e849b3a-209c-455c-c45f-5324ac3c9033" 133 | }, 134 | "outputs": [ 135 | { 136 | "name": "stdout", 137 | "output_type": "stream", 138 | "text": [ 139 | "[('Three', 'CARDINAL'), ('more', ''), ('countries', ''), ('have', ''), ('joined', ''), ('an', ''), ('“', ''), ('international', ''), ('grand', ''), ('committee', ''), ('”', ''), ('of', ''), ('parliaments', ''), (',', ''), ('adding', ''), ('to', ''), ('calls', ''), ('for', ''), ('Facebook', ''), ('’s', ''), ('boss', ''), (',', ''), ('Mark', 'PERSON'), ('Zuckerberg', 'PERSON'), (',', ''), ('to', ''), ('give', ''), ('evidence', ''), ('on', ''), ('misinformation', ''), ('to', ''), ('the', ''), ('coalition', ''), ('.', ''), ('Brazil', 'GPE'), (',', ''), ('Latvia', 'GPE'), ('and', ''), ('Singapore', 'GPE'), ('bring', ''), ('the', ''), ('total', ''), ('to', ''), ('eight', 'CARDINAL'), ('different', ''), ('parliaments', ''), ('across', ''), ('the', ''), ('world', ''), (',', ''), ('with', ''), ('plans', ''), ('to', ''), ('send', ''), ('representatives', ''), ('to', ''), ('London', 'GPE'), ('on', ''), ('27', 'DATE'), ('November', 'DATE'), ('with', ''), ('the', ''), ('intention', ''), ('of', ''), ('hearing', ''), ('from', ''), ('Zuckerberg', 'GPE'), ('.', ''), ('Since', ''), ('the', ''), ('Cambridge', ''), ('Analytica', ''), ('scandal', ''), ('broke', ''), (',', ''), ('the', ''), ('Facebook', 'ORG'), ('chief', ''), ('has', ''), ('only', ''), ('appeared', ''), ('in', ''), ('front', ''), ('of', ''), ('two', 'CARDINAL'), ('legislatures', ''), (':', ''), ('the', 'ORG'), ('American', 'ORG'), ('Senate', 'ORG'), ('and', ''), ('House', 'ORG'), ('of', 'ORG'), ('Representatives', 'ORG'), (',', ''), ('and', ''), ('the', ''), ('European', 'NORP'), ('parliament', ''), ('.', ''), ('Facebook', ''), ('has', ''), ('consistently', ''), ('rebuffed', ''), ('attempts', ''), ('from', ''), ('others', ''), (',', ''), ('including', ''), ('the', ''), ('UK', 'GPE'), ('and', ''), ('Canadian', 'NORP'), ('parliaments', ''), (',', ''), ('to', ''), ('hear', ''), ('from', ''), ('Zuckerberg', 'GPE'), ('.', ''), ('He', ''), ('added', ''), ('that', ''), ('an', ''), ('article', ''), ('in', ''), ('the', 'ORG'), ('New', 'ORG'), ('York', 'ORG'), ('Times', 'ORG'), ('on', ''), ('Thursday', 'DATE'), (',', ''), ('in', ''), ('which', ''), ('the', ''), ('paper', ''), ('alleged', ''), ('a', ''), ('pattern', ''), ('of', ''), ('behaviour', ''), ('from', ''), ('Facebook', 'ORG'), ('to', ''), ('“', ''), ('delay', ''), (',', ''), ('deny', ''), ('and', ''), ('deflect', ''), ('”', ''), ('negative', ''), ('news', ''), ('stories', ''), (',', ''), ('“', ''), ('raises', ''), ('further', ''), ('questions', ''), ('about', ''), ('how', ''), ('recent', ''), ('data', ''), ('breaches', ''), ('were', ''), ('allegedly', ''), ('dealt', ''), ('with', ''), ('within', ''), ('Facebook', 'ORG'), ('.', ''), ('”', '')]\n" 140 | ] 141 | } 142 | ], 143 | "source": [ 144 | "# print named entities in article\n", 145 | "ner_tagged = [(word.text, word.ent_type_) for word in text_nlp]\n", 146 | "print(ner_tagged)" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": 5, 152 | "metadata": { 153 | "colab": { 154 | "base_uri": "https://localhost:8080/", 155 | "height": 223 156 | }, 157 | "colab_type": "code", 158 | "id": "m_E-aMCgWkwJ", 159 | "outputId": "3f36bcf2-858c-4904-9464-c8ea58c741d1" 160 | }, 161 | "outputs": [ 162 | { 163 | "data": { 164 | "text/html": [ 165 | "
\n", 166 | "\n", 167 | " Three\n", 168 | " CARDINAL\n", 169 | "\n", 170 | " more countries have joined an “international grand committee” of parliaments, adding to calls for Facebook’s boss, \n", 171 | "\n", 172 | " Mark Zuckerberg\n", 173 | " PERSON\n", 174 | "\n", 175 | ", to give evidence on misinformation to the coalition. \n", 176 | "\n", 177 | " Brazil\n", 178 | " GPE\n", 179 | "\n", 180 | ", \n", 181 | "\n", 182 | " Latvia\n", 183 | " GPE\n", 184 | "\n", 185 | " and \n", 186 | "\n", 187 | " Singapore\n", 188 | " GPE\n", 189 | "\n", 190 | " bring the total to \n", 191 | "\n", 192 | " eight\n", 193 | " CARDINAL\n", 194 | "\n", 195 | " different parliaments across the world, with plans to send representatives to \n", 196 | "\n", 197 | " London\n", 198 | " GPE\n", 199 | "\n", 200 | " on \n", 201 | "\n", 202 | " 27 November\n", 203 | " DATE\n", 204 | "\n", 205 | " with the intention of hearing from \n", 206 | "\n", 207 | " Zuckerberg\n", 208 | " GPE\n", 209 | "\n", 210 | ". Since the Cambridge Analytica scandal broke, the \n", 211 | "\n", 212 | " Facebook\n", 213 | " ORG\n", 214 | "\n", 215 | " chief has only appeared in front of \n", 216 | "\n", 217 | " two\n", 218 | " CARDINAL\n", 219 | "\n", 220 | " legislatures: \n", 221 | "\n", 222 | " the American Senate\n", 223 | " ORG\n", 224 | "\n", 225 | " and \n", 226 | "\n", 227 | " House of Representatives\n", 228 | " ORG\n", 229 | "\n", 230 | ", and the \n", 231 | "\n", 232 | " European\n", 233 | " NORP\n", 234 | "\n", 235 | " parliament. Facebook has consistently rebuffed attempts from others, including the \n", 236 | "\n", 237 | " UK\n", 238 | " GPE\n", 239 | "\n", 240 | " and \n", 241 | "\n", 242 | " Canadian\n", 243 | " NORP\n", 244 | "\n", 245 | " parliaments, to hear from \n", 246 | "\n", 247 | " Zuckerberg\n", 248 | " GPE\n", 249 | "\n", 250 | ". He added that an article in \n", 251 | "\n", 252 | " the New York Times\n", 253 | " ORG\n", 254 | "\n", 255 | " on \n", 256 | "\n", 257 | " Thursday\n", 258 | " DATE\n", 259 | "\n", 260 | ", in which the paper alleged a pattern of behaviour from \n", 261 | "\n", 262 | " Facebook\n", 263 | " ORG\n", 264 | "\n", 265 | " to “delay, deny and deflect” negative news stories, “raises further questions about how recent data breaches were allegedly dealt with within \n", 266 | "\n", 267 | " Facebook\n", 268 | " ORG\n", 269 | "\n", 270 | ".”
" 271 | ], 272 | "text/plain": [ 273 | "" 274 | ] 275 | }, 276 | "metadata": { 277 | "tags": [] 278 | }, 279 | "output_type": "display_data" 280 | } 281 | ], 282 | "source": [ 283 | "from spacy import displacy\n", 284 | "\n", 285 | "# visualize named entities\n", 286 | "displacy.render(text_nlp, style='ent', jupyter=True)" 287 | ] 288 | }, 289 | { 290 | "cell_type": "markdown", 291 | "metadata": { 292 | "colab_type": "text", 293 | "id": "rOWeUtk6WkwL" 294 | }, 295 | "source": [ 296 | "Spacy offers fast NER tagger based on a number of techniques. The exact algorithm hasn't been talked about in much detail but the documentation marks it as \"The exact algorithm is a pastiche of well-known methods, and is not currently described in any single publication \" \n", 297 | "\n", 298 | "The entities identified by spacy NER tagger are as shown in the following table \\(details here: [spacy_documentation](https://spacy.io/api/annotation#named-entities)\\)\n", 299 | "\n", 300 | "![](https://github.com/dipanjanS/nlp_workshop_odsc19/blob/master/Module03%20-%20Text%20Understanding/Resources/spacy_ner.png?raw=1)" 301 | ] 302 | }, 303 | { 304 | "cell_type": "code", 305 | "execution_count": 0, 306 | "metadata": { 307 | "colab": {}, 308 | "colab_type": "code", 309 | "id": "LwTRhs43WkwM" 310 | }, 311 | "outputs": [], 312 | "source": [ 313 | "named_entities = []\n", 314 | "temp_entity_name = ''\n", 315 | "temp_named_entity = None\n", 316 | "for term, tag in ner_tagged:\n", 317 | " if tag:\n", 318 | " temp_entity_name = ' '.join([temp_entity_name, term]).strip()\n", 319 | " temp_named_entity = (temp_entity_name, tag)\n", 320 | " else:\n", 321 | " if temp_named_entity:\n", 322 | " named_entities.append(temp_named_entity)\n", 323 | " temp_entity_name = ''\n", 324 | " temp_named_entity = None" 325 | ] 326 | }, 327 | { 328 | "cell_type": "code", 329 | "execution_count": 7, 330 | "metadata": { 331 | "colab": { 332 | "base_uri": "https://localhost:8080/", 333 | "height": 54 334 | }, 335 | "colab_type": "code", 336 | "id": "VFbN8w73WkwO", 337 | "outputId": "fa2961e0-1897-4a88-f2ae-8a5857cca784" 338 | }, 339 | "outputs": [ 340 | { 341 | "name": "stdout", 342 | "output_type": "stream", 343 | "text": [ 344 | "[('Three', 'CARDINAL'), ('Mark Zuckerberg', 'PERSON'), ('Brazil', 'GPE'), ('Latvia', 'GPE'), ('Singapore', 'GPE'), ('eight', 'CARDINAL'), ('London', 'GPE'), ('27 November', 'DATE'), ('Zuckerberg', 'GPE'), ('Facebook', 'ORG'), ('two', 'CARDINAL'), ('the American Senate', 'ORG'), ('House of Representatives', 'ORG'), ('European', 'NORP'), ('UK', 'GPE'), ('Canadian', 'NORP'), ('Zuckerberg', 'GPE'), ('the New York Times', 'ORG'), ('Thursday', 'DATE'), ('Facebook', 'ORG'), ('Facebook', 'ORG')]\n" 345 | ] 346 | } 347 | ], 348 | "source": [ 349 | "print(named_entities)" 350 | ] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": 8, 355 | "metadata": { 356 | "colab": { 357 | "base_uri": "https://localhost:8080/", 358 | "height": 118 359 | }, 360 | "colab_type": "code", 361 | "id": "bcUB1xmRWkwQ", 362 | "outputId": "6f1deb3e-3eec-434d-a04e-6d741a5b6813" 363 | }, 364 | "outputs": [ 365 | { 366 | "data": { 367 | "text/plain": [ 368 | "[('GPE', 7),\n", 369 | " ('ORG', 6),\n", 370 | " ('CARDINAL', 3),\n", 371 | " ('DATE', 2),\n", 372 | " ('NORP', 2),\n", 373 | " ('PERSON', 1)]" 374 | ] 375 | }, 376 | "execution_count": 8, 377 | "metadata": { 378 | "tags": [] 379 | }, 380 | "output_type": "execute_result" 381 | } 382 | ], 383 | "source": [ 384 | "from collections import Counter\n", 385 | "c = Counter([item[1] for item in named_entities])\n", 386 | "c.most_common()" 387 | ] 388 | }, 389 | { 390 | "cell_type": "markdown", 391 | "metadata": { 392 | "colab_type": "text", 393 | "id": "LiYFy54bXUFD" 394 | }, 395 | "source": [ 396 | "## Training your own NER Models\n", 397 | "\n", 398 | "1. Conditional Random Field based models -> `sklearn crfsuite` (check my GitHub \\ Google)\n", 399 | "2. Sequntial Deep Learning Models (bi-LSTMs, Transformers)\n", 400 | "3. Spacy has training capabilities -> https://spacy.io/usage/training#ner" 401 | ] 402 | } 403 | ], 404 | "metadata": { 405 | "colab": { 406 | "collapsed_sections": [], 407 | "name": "03-Introduction to NLP - Named Entity Recognition.ipynb", 408 | "provenance": [] 409 | }, 410 | "kernelspec": { 411 | "display_name": "Python 3", 412 | "language": "python", 413 | "name": "python3" 414 | }, 415 | "language_info": { 416 | "codemirror_mode": { 417 | "name": "ipython", 418 | "version": 3 419 | }, 420 | "file_extension": ".py", 421 | "mimetype": "text/x-python", 422 | "name": "python", 423 | "nbconvert_exporter": "python", 424 | "pygments_lexer": "ipython3", 425 | "version": "3.7.6" 426 | } 427 | }, 428 | "nbformat": 4, 429 | "nbformat_minor": 1 430 | } 431 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /tutorials/03_NLP Applications/10_NLP_Applications_Text_Classification_Deep_Learning_CNN_Models.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "colab_type": "text", 7 | "id": "f64bBXyhpxTR" 8 | }, 9 | "source": [ 10 | "# Text Classification - Deep Learning CNN Models\n", 11 | "\n", 12 | "\n", 13 | "\n", 14 | "When it comes to text data, sentiment analysis is one of the most widely performed analysis on it. Sentiment Analysis has been through tremendous improvements from the days of classic methods to recent times where in the state of the art models utilize deep learning to improve the performance.\n", 15 | "\n", 16 | "Convolutional Neural Networks or CNNs are the work-horse of the deep learning world. They have, in some sense, brought deep learning research into mainstream discussions. The advancements in the image classification world has left even humans behind.\n", 17 | "\n", 18 | "\n", 19 | "In this project, we will attempt at performing sentiment analysis utilizing the power of CNNs." 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 1, 25 | "metadata": { 26 | "colab": { 27 | "base_uri": "https://localhost:8080/", 28 | "height": 420 29 | }, 30 | "colab_type": "code", 31 | "id": "iayiP3GZrjjk", 32 | "outputId": "0156a404-33b7-4e53-ec9c-a28ab019732e" 33 | }, 34 | "outputs": [ 35 | { 36 | "name": "stdout", 37 | "output_type": "stream", 38 | "text": [ 39 | "Collecting contractions\n", 40 | " Downloading https://files.pythonhosted.org/packages/85/41/c3dfd5feb91a8d587ed1a59f553f07c05f95ad4e5d00ab78702fbf8fe48a/contractions-0.0.24-py2.py3-none-any.whl\n", 41 | "Collecting textsearch\n", 42 | " Downloading https://files.pythonhosted.org/packages/42/a8/03407021f9555043de5492a2bd7a35c56cc03c2510092b5ec018cae1bbf1/textsearch-0.0.17-py2.py3-none-any.whl\n", 43 | "Collecting pyahocorasick\n", 44 | "\u001b[?25l Downloading https://files.pythonhosted.org/packages/f4/9f/f0d8e8850e12829eea2e778f1c90e3c53a9a799b7f412082a5d21cd19ae1/pyahocorasick-1.4.0.tar.gz (312kB)\n", 45 | "\u001b[K |████████████████████████████████| 317kB 12.3MB/s \n", 46 | "\u001b[?25hCollecting Unidecode\n", 47 | "\u001b[?25l Downloading https://files.pythonhosted.org/packages/d0/42/d9edfed04228bacea2d824904cae367ee9efd05e6cce7ceaaedd0b0ad964/Unidecode-1.1.1-py2.py3-none-any.whl (238kB)\n", 48 | "\u001b[K |████████████████████████████████| 245kB 22.0MB/s \n", 49 | "\u001b[?25hBuilding wheels for collected packages: pyahocorasick\n", 50 | " Building wheel for pyahocorasick (setup.py) ... \u001b[?25l\u001b[?25hdone\n", 51 | " Created wheel for pyahocorasick: filename=pyahocorasick-1.4.0-cp36-cp36m-linux_x86_64.whl size=81692 sha256=f01a1dfd242fadf9ac9f5c58e0da5f43b45df82f1e6d24d37eaf0c773b772564\n", 52 | " Stored in directory: /root/.cache/pip/wheels/0a/90/61/87a55f5b459792fbb2b7ba6b31721b06ff5cf6bde541b40994\n", 53 | "Successfully built pyahocorasick\n", 54 | "Installing collected packages: pyahocorasick, Unidecode, textsearch, contractions\n", 55 | "Successfully installed Unidecode-1.1.1 contractions-0.0.24 pyahocorasick-1.4.0 textsearch-0.0.17\n", 56 | "Requirement already satisfied: textsearch in /usr/local/lib/python3.6/dist-packages (0.0.17)\n", 57 | "Requirement already satisfied: Unidecode in /usr/local/lib/python3.6/dist-packages (from textsearch) (1.1.1)\n", 58 | "Requirement already satisfied: pyahocorasick in /usr/local/lib/python3.6/dist-packages (from textsearch) (1.4.0)\n", 59 | "Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (4.41.1)\n", 60 | "[nltk_data] Downloading package punkt to /root/nltk_data...\n", 61 | "[nltk_data] Unzipping tokenizers/punkt.zip.\n" 62 | ] 63 | }, 64 | { 65 | "data": { 66 | "text/plain": [ 67 | "True" 68 | ] 69 | }, 70 | "execution_count": 1, 71 | "metadata": { 72 | "tags": [] 73 | }, 74 | "output_type": "execute_result" 75 | } 76 | ], 77 | "source": [ 78 | "!pip install contractions\n", 79 | "!pip install textsearch\n", 80 | "!pip install tqdm\n", 81 | "import nltk\n", 82 | "nltk.download('punkt')" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": 0, 88 | "metadata": { 89 | "colab": {}, 90 | "colab_type": "code", 91 | "id": "Gbnh0egkUzRX" 92 | }, 93 | "outputs": [], 94 | "source": [ 95 | "import pandas as pd\n", 96 | "import numpy as np\n", 97 | "from tensorflow.keras.models import Sequential\n", 98 | "from tensorflow.keras.layers import Dense\n", 99 | "from tensorflow.keras.layers import Flatten\n", 100 | "from tensorflow.keras.layers import Conv1D\n", 101 | "from tensorflow.keras.layers import MaxPooling1D\n", 102 | "from tensorflow.keras.layers import Embedding\n", 103 | "from tensorflow.keras.preprocessing.text import Tokenizer\n", 104 | "from tensorflow.keras.preprocessing import sequence\n", 105 | "from sklearn.preprocessing import LabelEncoder\n", 106 | "import tensorflow as tf\n", 107 | "\n", 108 | "# fix random seed for reproducibility\n", 109 | "seed = 42\n", 110 | "np.random.seed(seed)" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": { 116 | "colab_type": "text", 117 | "id": "8_JEXODppxTc" 118 | }, 119 | "source": [ 120 | "## Load Movie Review Dataset" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": 3, 126 | "metadata": { 127 | "colab": { 128 | "base_uri": "https://localhost:8080/", 129 | "height": 168 130 | }, 131 | "colab_type": "code", 132 | "id": "U7pQ5WR1VYqm", 133 | "outputId": "768b6838-021e-4d9d-eb59-93e94f205384" 134 | }, 135 | "outputs": [ 136 | { 137 | "name": "stdout", 138 | "output_type": "stream", 139 | "text": [ 140 | "\n", 141 | "RangeIndex: 50000 entries, 0 to 49999\n", 142 | "Data columns (total 2 columns):\n", 143 | " # Column Non-Null Count Dtype \n", 144 | "--- ------ -------------- ----- \n", 145 | " 0 review 50000 non-null object\n", 146 | " 1 sentiment 50000 non-null object\n", 147 | "dtypes: object(2)\n", 148 | "memory usage: 781.4+ KB\n" 149 | ] 150 | } 151 | ], 152 | "source": [ 153 | "dataset = pd.read_csv(r'https://github.com/dipanjanS/nlp_workshop_dhs18/raw/master/Unit%2011%20-%20Sentiment%20Analysis%20-%20Unsupervised%20Learning/movie_reviews.csv.bz2', compression='bz2')\n", 154 | "dataset.info()" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": 4, 160 | "metadata": { 161 | "colab": { 162 | "base_uri": "https://localhost:8080/", 163 | "height": 195 164 | }, 165 | "colab_type": "code", 166 | "id": "XMP7r5cUV6-B", 167 | "outputId": "c3aa795d-e09c-43ad-fb70-da185b4e997b" 168 | }, 169 | "outputs": [ 170 | { 171 | "data": { 172 | "text/html": [ 173 | "
\n", 174 | "\n", 187 | "\n", 188 | " \n", 189 | " \n", 190 | " \n", 191 | " \n", 192 | " \n", 193 | " \n", 194 | " \n", 195 | " \n", 196 | " \n", 197 | " \n", 198 | " \n", 199 | " \n", 200 | " \n", 201 | " \n", 202 | " \n", 203 | " \n", 204 | " \n", 205 | " \n", 206 | " \n", 207 | " \n", 208 | " \n", 209 | " \n", 210 | " \n", 211 | " \n", 212 | " \n", 213 | " \n", 214 | " \n", 215 | " \n", 216 | " \n", 217 | " \n", 218 | " \n", 219 | " \n", 220 | " \n", 221 | " \n", 222 | "
reviewsentiment
0One of the other reviewers has mentioned that ...positive
1A wonderful little production. <br /><br />The...positive
2I thought this was a wonderful way to spend ti...positive
3Basically there's a family where a little boy ...negative
4Petter Mattei's \"Love in the Time of Money\" is...positive
\n", 223 | "
" 224 | ], 225 | "text/plain": [ 226 | " review sentiment\n", 227 | "0 One of the other reviewers has mentioned that ... positive\n", 228 | "1 A wonderful little production.

The... positive\n", 229 | "2 I thought this was a wonderful way to spend ti... positive\n", 230 | "3 Basically there's a family where a little boy ... negative\n", 231 | "4 Petter Mattei's \"Love in the Time of Money\" is... positive" 232 | ] 233 | }, 234 | "execution_count": 4, 235 | "metadata": { 236 | "tags": [] 237 | }, 238 | "output_type": "execute_result" 239 | } 240 | ], 241 | "source": [ 242 | "# take a peek at the data\n", 243 | "dataset.head()" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "metadata": { 249 | "colab_type": "text", 250 | "id": "-qBM4Od_pxTp" 251 | }, 252 | "source": [ 253 | "### Prepare Train Test Split" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": 0, 259 | "metadata": { 260 | "colab": {}, 261 | "colab_type": "code", 262 | "id": "XpwueLn6V-qF" 263 | }, 264 | "outputs": [], 265 | "source": [ 266 | "# build train and test datasets\n", 267 | "reviews = dataset['review'].values\n", 268 | "sentiments = dataset['sentiment'].values\n", 269 | "\n", 270 | "train_reviews = reviews[:35000]\n", 271 | "train_sentiments = sentiments[:35000]\n", 272 | "\n", 273 | "test_reviews = reviews[35000:]\n", 274 | "test_sentiments = sentiments[35000:]" 275 | ] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "metadata": { 280 | "colab_type": "text", 281 | "id": "CETaiGM2tO_d" 282 | }, 283 | "source": [ 284 | "# Text Wrangling & Normalization" 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "execution_count": 0, 290 | "metadata": { 291 | "colab": {}, 292 | "colab_type": "code", 293 | "id": "tkFyu9u3tUOi" 294 | }, 295 | "outputs": [], 296 | "source": [ 297 | "import contractions\n", 298 | "from bs4 import BeautifulSoup\n", 299 | "import numpy as np\n", 300 | "import re\n", 301 | "import tqdm\n", 302 | "import unicodedata\n", 303 | "\n", 304 | "\n", 305 | "def strip_html_tags(text):\n", 306 | " soup = BeautifulSoup(text, \"html.parser\")\n", 307 | " [s.extract() for s in soup(['iframe', 'script'])]\n", 308 | " stripped_text = soup.get_text()\n", 309 | " stripped_text = re.sub(r'[\\r|\\n|\\r\\n]+', '\\n', stripped_text)\n", 310 | " return stripped_text\n", 311 | "\n", 312 | "def remove_accented_chars(text):\n", 313 | " text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8', 'ignore')\n", 314 | " return text\n", 315 | "\n", 316 | "def pre_process_corpus(docs):\n", 317 | " norm_docs = []\n", 318 | " for doc in tqdm.tqdm(docs):\n", 319 | " doc = strip_html_tags(doc)\n", 320 | " doc = doc.translate(doc.maketrans(\"\\n\\t\\r\", \" \"))\n", 321 | " doc = doc.lower()\n", 322 | " doc = remove_accented_chars(doc)\n", 323 | " doc = contractions.fix(doc)\n", 324 | " # lower case and remove special characters\\whitespaces\n", 325 | " doc = re.sub(r'[^a-zA-Z0-9\\s]', '', doc, re.I|re.A)\n", 326 | " doc = re.sub(' +', ' ', doc)\n", 327 | " doc = doc.strip() \n", 328 | " norm_docs.append(doc)\n", 329 | " \n", 330 | " return norm_docs" 331 | ] 332 | }, 333 | { 334 | "cell_type": "code", 335 | "execution_count": 7, 336 | "metadata": { 337 | "colab": { 338 | "base_uri": "https://localhost:8080/", 339 | "height": 84 340 | }, 341 | "colab_type": "code", 342 | "id": "EgAqgSnHtap5", 343 | "outputId": "388af7f0-bd24-4829-8554-4b02f9cb5108" 344 | }, 345 | "outputs": [ 346 | { 347 | "name": "stderr", 348 | "output_type": "stream", 349 | "text": [ 350 | "100%|██████████| 35000/35000 [00:14<00:00, 2412.80it/s]\n", 351 | "100%|██████████| 15000/15000 [00:06<00:00, 2402.68it/s]" 352 | ] 353 | }, 354 | { 355 | "name": "stdout", 356 | "output_type": "stream", 357 | "text": [ 358 | "CPU times: user 20.6 s, sys: 112 ms, total: 20.8 s\n", 359 | "Wall time: 20.8 s\n" 360 | ] 361 | }, 362 | { 363 | "name": "stderr", 364 | "output_type": "stream", 365 | "text": [ 366 | "\n" 367 | ] 368 | } 369 | ], 370 | "source": [ 371 | "%%time\n", 372 | "\n", 373 | "norm_train_reviews = pre_process_corpus(train_reviews)\n", 374 | "norm_test_reviews = pre_process_corpus(test_reviews)" 375 | ] 376 | }, 377 | { 378 | "cell_type": "markdown", 379 | "metadata": { 380 | "colab_type": "text", 381 | "id": "COgKPRmLpxTu" 382 | }, 383 | "source": [ 384 | "## Preprocessing\n", 385 | "\n", 386 | "To prepare text data for our deep learning model, we transform each review into a sequence.\n", 387 | "Every word in the review is mapped to an integer index and thus the sentence turns into a sequence of numbers.\n", 388 | "\n", 389 | "To perform this transformation, keras provides the ```Tokenizer```" 390 | ] 391 | }, 392 | { 393 | "cell_type": "code", 394 | "execution_count": 0, 395 | "metadata": { 396 | "colab": {}, 397 | "colab_type": "code", 398 | "id": "dff8sG63cw03" 399 | }, 400 | "outputs": [], 401 | "source": [ 402 | "t = Tokenizer(oov_token='')\n", 403 | "# fit the tokenizer on the documents\n", 404 | "t.fit_on_texts(norm_train_reviews)\n", 405 | "t.word_index[''] = 0" 406 | ] 407 | }, 408 | { 409 | "cell_type": "code", 410 | "execution_count": 9, 411 | "metadata": { 412 | "colab": { 413 | "base_uri": "https://localhost:8080/", 414 | "height": 34 415 | }, 416 | "colab_type": "code", 417 | "id": "0xd_eGZ1vQRR", 418 | "outputId": "7c0b2b5d-43f0-4757-a9d0-5426b3de01c0" 419 | }, 420 | "outputs": [ 421 | { 422 | "data": { 423 | "text/plain": [ 424 | "(('dawgis', 175859), ('', 0), 1)" 425 | ] 426 | }, 427 | "execution_count": 9, 428 | "metadata": { 429 | "tags": [] 430 | }, 431 | "output_type": "execute_result" 432 | } 433 | ], 434 | "source": [ 435 | "max([(k, v) for k, v in t.word_index.items()], key = lambda x:x[1]), min([(k, v) for k, v in t.word_index.items()], key = lambda x:x[1]), t.word_index['']" 436 | ] 437 | }, 438 | { 439 | "cell_type": "code", 440 | "execution_count": 0, 441 | "metadata": { 442 | "colab": {}, 443 | "colab_type": "code", 444 | "id": "4yv_m8T5c2xg" 445 | }, 446 | "outputs": [], 447 | "source": [ 448 | "train_sequences = t.texts_to_sequences(norm_train_reviews)" 449 | ] 450 | }, 451 | { 452 | "cell_type": "code", 453 | "execution_count": 0, 454 | "metadata": { 455 | "colab": {}, 456 | "colab_type": "code", 457 | "id": "ifZCCxtydEnc" 458 | }, 459 | "outputs": [], 460 | "source": [ 461 | "test_sequences = t.texts_to_sequences(norm_test_reviews)" 462 | ] 463 | }, 464 | { 465 | "cell_type": "code", 466 | "execution_count": 12, 467 | "metadata": { 468 | "colab": { 469 | "base_uri": "https://localhost:8080/", 470 | "height": 50 471 | }, 472 | "colab_type": "code", 473 | "id": "ldkDHyjZgaFV", 474 | "outputId": "0ee278a3-b63f-4d1a-9a25-21faca939cc1" 475 | }, 476 | "outputs": [ 477 | { 478 | "name": "stdout", 479 | "output_type": "stream", 480 | "text": [ 481 | "Vocabulary size=175860\n", 482 | "Number of Documents=35000\n" 483 | ] 484 | } 485 | ], 486 | "source": [ 487 | "print(\"Vocabulary size={}\".format(len(t.word_index)))\n", 488 | "print(\"Number of Documents={}\".format(t.document_count))" 489 | ] 490 | }, 491 | { 492 | "cell_type": "code", 493 | "execution_count": 13, 494 | "metadata": { 495 | "colab": { 496 | "base_uri": "https://localhost:8080/", 497 | "height": 374 498 | }, 499 | "colab_type": "code", 500 | "id": "CQjiXA7Ntw13", 501 | "outputId": "c70b1f93-c18a-4661-cac5-e9d2c709d54c" 502 | }, 503 | "outputs": [ 504 | { 505 | "data": { 506 | "image/png": "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\n", 507 | "text/plain": [ 508 | "
" 509 | ] 510 | }, 511 | "metadata": { 512 | "needs_background": "light", 513 | "tags": [] 514 | }, 515 | "output_type": "display_data" 516 | } 517 | ], 518 | "source": [ 519 | "import matplotlib.pyplot as plt\n", 520 | "%matplotlib inline\n", 521 | "\n", 522 | "train_lens = [len(s) for s in train_sequences]\n", 523 | "test_lens = [len(s) for s in test_sequences]\n", 524 | "\n", 525 | "fig, ax = plt.subplots(1,2, figsize=(12, 6))\n", 526 | "h1 = ax[0].hist(train_lens)\n", 527 | "h2 = ax[1].hist(test_lens)" 528 | ] 529 | }, 530 | { 531 | "cell_type": "markdown", 532 | "metadata": { 533 | "colab_type": "text", 534 | "id": "xfZwP6C8pxT8" 535 | }, 536 | "source": [ 537 | "### Sequence Normalization\n", 538 | "\n", 539 | "Not all reviews are of same length. To handle this difference in length of reviews, we define a maximum length.\n", 540 | "For reviews which are smaller than this length, we pad them with zeros which longer ones are truncated" 541 | ] 542 | }, 543 | { 544 | "cell_type": "code", 545 | "execution_count": 0, 546 | "metadata": { 547 | "colab": {}, 548 | "colab_type": "code", 549 | "id": "BtuGJ0wXjQnC" 550 | }, 551 | "outputs": [], 552 | "source": [ 553 | "MAX_SEQUENCE_LENGTH = 1000" 554 | ] 555 | }, 556 | { 557 | "cell_type": "code", 558 | "execution_count": 15, 559 | "metadata": { 560 | "colab": { 561 | "base_uri": "https://localhost:8080/", 562 | "height": 34 563 | }, 564 | "colab_type": "code", 565 | "id": "wAnv99kzWA5k", 566 | "outputId": "5664d25d-f09f-4c8c-a745-e2d8d6bf2dec" 567 | }, 568 | "outputs": [ 569 | { 570 | "data": { 571 | "text/plain": [ 572 | "((35000, 1000), (15000, 1000))" 573 | ] 574 | }, 575 | "execution_count": 15, 576 | "metadata": { 577 | "tags": [] 578 | }, 579 | "output_type": "execute_result" 580 | } 581 | ], 582 | "source": [ 583 | "# pad dataset to a maximum review length in words\n", 584 | "X_train = sequence.pad_sequences(train_sequences, maxlen=MAX_SEQUENCE_LENGTH)\n", 585 | "X_test = sequence.pad_sequences(test_sequences, maxlen=MAX_SEQUENCE_LENGTH)\n", 586 | "X_train.shape, X_test.shape" 587 | ] 588 | }, 589 | { 590 | "cell_type": "markdown", 591 | "metadata": { 592 | "colab_type": "text", 593 | "id": "9X_4ticSpxUC" 594 | }, 595 | "source": [ 596 | "### Encoding Labels\n", 597 | "\n", 598 | "The dataset contains labels of the form positive/negative. The following step encodes the labels using ```sklearn's``` ```LabelEncoder```" 599 | ] 600 | }, 601 | { 602 | "cell_type": "code", 603 | "execution_count": 0, 604 | "metadata": { 605 | "colab": {}, 606 | "colab_type": "code", 607 | "id": "rRMaWb1ldqyl" 608 | }, 609 | "outputs": [], 610 | "source": [ 611 | "le = LabelEncoder()\n", 612 | "num_classes=2 # positive -> 1, negative -> 0" 613 | ] 614 | }, 615 | { 616 | "cell_type": "code", 617 | "execution_count": 0, 618 | "metadata": { 619 | "colab": {}, 620 | "colab_type": "code", 621 | "id": "tJjbtyDjfsd1" 622 | }, 623 | "outputs": [], 624 | "source": [ 625 | "y_train = le.fit_transform(train_sentiments)\n", 626 | "y_test = le.transform(test_sentiments)" 627 | ] 628 | }, 629 | { 630 | "cell_type": "code", 631 | "execution_count": 0, 632 | "metadata": { 633 | "colab": {}, 634 | "colab_type": "code", 635 | "id": "iaqFz7ZpdoLC" 636 | }, 637 | "outputs": [], 638 | "source": [ 639 | "VOCAB_SIZE = len(t.word_index)" 640 | ] 641 | }, 642 | { 643 | "cell_type": "markdown", 644 | "metadata": { 645 | "colab_type": "text", 646 | "id": "YCjRYBh2pxUM" 647 | }, 648 | "source": [ 649 | "# Prepare the Model\n", 650 | "\n", 651 | "Since textual data is a sequence of words, we utilize ```1D``` convolutions to scan through the sentences.\n", 652 | "The model first transforms each word into lower dimensional embedding/vector space followed by 1d convolutions and then passing the data through dense layers before the final layer for classification\n", 653 | "\n", 654 | "## Embeddings\n", 655 | "\n", 656 | "The Embedding layer helps us generate the word embeddings from scratch. This layer\n", 657 | "is also initialized with some weights and is updated based on our optimizer, similar to\n", 658 | "weights on the neuron units in other layers when the network tries to minimize the loss\n", 659 | "in each epoch. Thus, the embedding layer tries to optimize its weights such that we get\n", 660 | "the best word embeddings that will generate minimum error in the model and capture\n", 661 | "semantic similarity and relationships among words. How do we get the embeddings?\n", 662 | "Let’s say we have a review with three terms ['movie', 'was', 'good'] and a vocab_map\n", 663 | "consisting of word to index mappings for 175860 words. \n", 664 | "\n", 665 | "![](https://i.imgur.com/WuV47DW.png)" 666 | ] 667 | }, 668 | { 669 | "cell_type": "code", 670 | "execution_count": 0, 671 | "metadata": { 672 | "colab": {}, 673 | "colab_type": "code", 674 | "id": "LR3mdd8kjgW1" 675 | }, 676 | "outputs": [], 677 | "source": [ 678 | "EMBED_SIZE = 300\n", 679 | "EPOCHS=10\n", 680 | "BATCH_SIZE=128" 681 | ] 682 | }, 683 | { 684 | "cell_type": "code", 685 | "execution_count": 20, 686 | "metadata": { 687 | "colab": { 688 | "base_uri": "https://localhost:8080/", 689 | "height": 487 690 | }, 691 | "colab_type": "code", 692 | "id": "AXhAERVeXhmZ", 693 | "outputId": "c16982e1-aa7d-4586-80d2-4e31857a3652" 694 | }, 695 | "outputs": [ 696 | { 697 | "name": "stdout", 698 | "output_type": "stream", 699 | "text": [ 700 | "Model: \"sequential\"\n", 701 | "_________________________________________________________________\n", 702 | "Layer (type) Output Shape Param # \n", 703 | "=================================================================\n", 704 | "embedding (Embedding) (None, 1000, 300) 52758000 \n", 705 | "_________________________________________________________________\n", 706 | "conv1d (Conv1D) (None, 1000, 128) 153728 \n", 707 | "_________________________________________________________________\n", 708 | "max_pooling1d (MaxPooling1D) (None, 500, 128) 0 \n", 709 | "_________________________________________________________________\n", 710 | "conv1d_1 (Conv1D) (None, 500, 64) 32832 \n", 711 | "_________________________________________________________________\n", 712 | "max_pooling1d_1 (MaxPooling1 (None, 250, 64) 0 \n", 713 | "_________________________________________________________________\n", 714 | "conv1d_2 (Conv1D) (None, 250, 32) 8224 \n", 715 | "_________________________________________________________________\n", 716 | "max_pooling1d_2 (MaxPooling1 (None, 125, 32) 0 \n", 717 | "_________________________________________________________________\n", 718 | "flatten (Flatten) (None, 4000) 0 \n", 719 | "_________________________________________________________________\n", 720 | "dense (Dense) (None, 256) 1024256 \n", 721 | "_________________________________________________________________\n", 722 | "dense_1 (Dense) (None, 1) 257 \n", 723 | "=================================================================\n", 724 | "Total params: 53,977,297\n", 725 | "Trainable params: 53,977,297\n", 726 | "Non-trainable params: 0\n", 727 | "_________________________________________________________________\n" 728 | ] 729 | } 730 | ], 731 | "source": [ 732 | "# create the model\n", 733 | "model = Sequential()\n", 734 | "model.add(Embedding(VOCAB_SIZE, EMBED_SIZE, input_length=MAX_SEQUENCE_LENGTH))\n", 735 | "model.add(Conv1D(filters=128, kernel_size=4, padding='same', activation='relu'))\n", 736 | "model.add(MaxPooling1D(pool_size=2))\n", 737 | "model.add(Conv1D(filters=64, kernel_size=4, padding='same', activation='relu'))\n", 738 | "model.add(MaxPooling1D(pool_size=2))\n", 739 | "model.add(Conv1D(filters=32, kernel_size=4, padding='same', activation='relu'))\n", 740 | "model.add(MaxPooling1D(pool_size=2))\n", 741 | "model.add(Flatten())\n", 742 | "model.add(Dense(256, activation='relu'))\n", 743 | "model.add(Dense(1, activation='sigmoid'))\n", 744 | "model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n", 745 | "model.summary()" 746 | ] 747 | }, 748 | { 749 | "cell_type": "markdown", 750 | "metadata": { 751 | "colab_type": "text", 752 | "id": "szNl8QiQpxUa" 753 | }, 754 | "source": [ 755 | "## Model Training" 756 | ] 757 | }, 758 | { 759 | "cell_type": "code", 760 | "execution_count": 21, 761 | "metadata": { 762 | "colab": { 763 | "base_uri": "https://localhost:8080/", 764 | "height": 168 765 | }, 766 | "colab_type": "code", 767 | "id": "0uc0jXszf5ob", 768 | "outputId": "08ff379f-3ac4-4982-d614-35e5a846113c" 769 | }, 770 | "outputs": [ 771 | { 772 | "name": "stdout", 773 | "output_type": "stream", 774 | "text": [ 775 | "Epoch 1/10\n", 776 | "247/247 [==============================] - 143s 578ms/step - loss: 0.3965 - accuracy: 0.7887 - val_loss: 0.2384 - val_accuracy: 0.9046\n", 777 | "Epoch 2/10\n", 778 | "247/247 [==============================] - 141s 570ms/step - loss: 0.1201 - accuracy: 0.9572 - val_loss: 0.2510 - val_accuracy: 0.9046\n", 779 | "Epoch 3/10\n", 780 | "247/247 [==============================] - ETA: 0s - loss: 0.0298 - accuracy: 0.9909Restoring model weights from the end of the best epoch.\n", 781 | "247/247 [==============================] - 142s 573ms/step - loss: 0.0298 - accuracy: 0.9909 - val_loss: 0.3914 - val_accuracy: 0.8994\n", 782 | "Epoch 00003: early stopping\n" 783 | ] 784 | }, 785 | { 786 | "data": { 787 | "text/plain": [ 788 | "" 789 | ] 790 | }, 791 | "execution_count": 21, 792 | "metadata": { 793 | "tags": [] 794 | }, 795 | "output_type": "execute_result" 796 | } 797 | ], 798 | "source": [ 799 | "# callbacks\n", 800 | "es = tf.keras.callbacks.EarlyStopping(monitor='val_loss', \n", 801 | " patience=2,\n", 802 | " restore_best_weights=True,\n", 803 | " verbose=1)\n", 804 | "\n", 805 | "# Fit the model\n", 806 | "model.fit(X_train, y_train, \n", 807 | " validation_split=0.1,\n", 808 | " epochs=EPOCHS, \n", 809 | " batch_size=BATCH_SIZE,\n", 810 | " callbacks=[es], \n", 811 | " verbose=1)" 812 | ] 813 | }, 814 | { 815 | "cell_type": "markdown", 816 | "metadata": { 817 | "colab_type": "text", 818 | "id": "cuKczZqYpxUk" 819 | }, 820 | "source": [ 821 | "## Model Evaluation" 822 | ] 823 | }, 824 | { 825 | "cell_type": "code", 826 | "execution_count": 22, 827 | "metadata": { 828 | "colab": { 829 | "base_uri": "https://localhost:8080/", 830 | "height": 50 831 | }, 832 | "colab_type": "code", 833 | "id": "3Zik9CWQgNlK", 834 | "outputId": "5a8971bc-20ef-4f75-8679-dac7f5fadf37" 835 | }, 836 | "outputs": [ 837 | { 838 | "name": "stdout", 839 | "output_type": "stream", 840 | "text": [ 841 | "469/469 [==============================] - 6s 14ms/step - loss: 0.2328 - accuracy: 0.9059\n", 842 | "Accuracy: 90.59%\n" 843 | ] 844 | } 845 | ], 846 | "source": [ 847 | "# Final evaluation of the model\n", 848 | "scores = model.evaluate(X_test, y_test, verbose=1)\n", 849 | "print(\"Accuracy: %.2f%%\" % (scores[1]*100))" 850 | ] 851 | }, 852 | { 853 | "cell_type": "code", 854 | "execution_count": 23, 855 | "metadata": { 856 | "colab": { 857 | "base_uri": "https://localhost:8080/", 858 | "height": 104 859 | }, 860 | "colab_type": "code", 861 | "id": "B904TLKNiA1B", 862 | "outputId": "e4b19799-00bd-4f96-8688-9cdff76dda1a" 863 | }, 864 | "outputs": [ 865 | { 866 | "name": "stdout", 867 | "output_type": "stream", 868 | "text": [ 869 | "WARNING:tensorflow:From :1: Sequential.predict_classes (from tensorflow.python.keras.engine.sequential) is deprecated and will be removed after 2021-01-01.\n", 870 | "Instructions for updating:\n", 871 | "Please use instead:* `np.argmax(model.predict(x), axis=-1)`, if your model does multi-class classification (e.g. if it uses a `softmax` last-layer activation).* `(model.predict(x) > 0.5).astype(\"int32\")`, if your model does binary classification (e.g. if it uses a `sigmoid` last-layer activation).\n" 872 | ] 873 | }, 874 | { 875 | "data": { 876 | "text/plain": [ 877 | "array([0, 1, 0, 1, 1, 0, 1, 1, 1, 1], dtype=int32)" 878 | ] 879 | }, 880 | "execution_count": 23, 881 | "metadata": { 882 | "tags": [] 883 | }, 884 | "output_type": "execute_result" 885 | } 886 | ], 887 | "source": [ 888 | "predictions = model.predict_classes(X_test).ravel()\n", 889 | "predictions[:10]" 890 | ] 891 | }, 892 | { 893 | "cell_type": "code", 894 | "execution_count": 24, 895 | "metadata": { 896 | "colab": { 897 | "base_uri": "https://localhost:8080/", 898 | "height": 185 899 | }, 900 | "colab_type": "code", 901 | "id": "HVjbqjaopxU-", 902 | "outputId": "119dbbcf-1d47-4a7f-ec3a-38173ca36da3" 903 | }, 904 | "outputs": [ 905 | { 906 | "data": { 907 | "text/plain": [ 908 | "['negative',\n", 909 | " 'positive',\n", 910 | " 'negative',\n", 911 | " 'positive',\n", 912 | " 'positive',\n", 913 | " 'negative',\n", 914 | " 'positive',\n", 915 | " 'positive',\n", 916 | " 'positive',\n", 917 | " 'positive']" 918 | ] 919 | }, 920 | "execution_count": 24, 921 | "metadata": { 922 | "tags": [] 923 | }, 924 | "output_type": "execute_result" 925 | } 926 | ], 927 | "source": [ 928 | "predictions = ['positive' if item == 1 else 'negative' for item in predictions]\n", 929 | "predictions[:10]" 930 | ] 931 | }, 932 | { 933 | "cell_type": "code", 934 | "execution_count": 25, 935 | "metadata": { 936 | "colab": { 937 | "base_uri": "https://localhost:8080/", 938 | "height": 258 939 | }, 940 | "colab_type": "code", 941 | "id": "mINpo7mDpxVC", 942 | "outputId": "646644fe-e736-46be-bf19-503c541dbcaa" 943 | }, 944 | "outputs": [ 945 | { 946 | "name": "stdout", 947 | "output_type": "stream", 948 | "text": [ 949 | " precision recall f1-score support\n", 950 | "\n", 951 | " negative 0.91 0.90 0.91 7490\n", 952 | " positive 0.90 0.91 0.91 7510\n", 953 | "\n", 954 | " accuracy 0.91 15000\n", 955 | " macro avg 0.91 0.91 0.91 15000\n", 956 | "weighted avg 0.91 0.91 0.91 15000\n", 957 | "\n" 958 | ] 959 | }, 960 | { 961 | "data": { 962 | "text/html": [ 963 | "
\n", 964 | "\n", 977 | "\n", 978 | " \n", 979 | " \n", 980 | " \n", 981 | " \n", 982 | " \n", 983 | " \n", 984 | " \n", 985 | " \n", 986 | " \n", 987 | " \n", 988 | " \n", 989 | " \n", 990 | " \n", 991 | " \n", 992 | " \n", 993 | " \n", 994 | " \n", 995 | " \n", 996 | " \n", 997 | "
negativepositive
negative6751739
positive6726838
\n", 998 | "
" 999 | ], 1000 | "text/plain": [ 1001 | " negative positive\n", 1002 | "negative 6751 739\n", 1003 | "positive 672 6838" 1004 | ] 1005 | }, 1006 | "execution_count": 25, 1007 | "metadata": { 1008 | "tags": [] 1009 | }, 1010 | "output_type": "execute_result" 1011 | } 1012 | ], 1013 | "source": [ 1014 | "from sklearn.metrics import confusion_matrix, classification_report\n", 1015 | "\n", 1016 | "labels = ['negative', 'positive']\n", 1017 | "print(classification_report(test_sentiments, predictions))\n", 1018 | "pd.DataFrame(confusion_matrix(test_sentiments, predictions), index=labels, columns=labels)" 1019 | ] 1020 | } 1021 | ], 1022 | "metadata": { 1023 | "accelerator": "GPU", 1024 | "anaconda-cloud": {}, 1025 | "colab": { 1026 | "collapsed_sections": [], 1027 | "name": "10-NLP Applications - Text Classification - Deep Learning CNN Models.ipynb", 1028 | "provenance": [] 1029 | }, 1030 | "kernelspec": { 1031 | "display_name": "Python 3", 1032 | "language": "python", 1033 | "name": "python3" 1034 | }, 1035 | "language_info": { 1036 | "codemirror_mode": { 1037 | "name": "ipython", 1038 | "version": 3 1039 | }, 1040 | "file_extension": ".py", 1041 | "mimetype": "text/x-python", 1042 | "name": "python", 1043 | "nbconvert_exporter": "python", 1044 | "pygments_lexer": "ipython3", 1045 | "version": "3.7.6" 1046 | } 1047 | }, 1048 | "nbformat": 4, 1049 | "nbformat_minor": 1 1050 | } 1051 | -------------------------------------------------------------------------------- /tutorials/01_Introduction to NLP/00_Introduction_to_NLP_Basics.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "colab_type": "text", 7 | "id": "TcDI2RgEBnn6" 8 | }, 9 | "source": [ 10 | "# String Types" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 1, 16 | "metadata": { 17 | "colab": { 18 | "base_uri": "https://localhost:8080/", 19 | "height": 67 20 | }, 21 | "colab_type": "code", 22 | "id": "ZY8-5FXhBnn7", 23 | "outputId": "1e195ea6-78b9-4da2-f3b9-632b9c53c44f" 24 | }, 25 | "outputs": [ 26 | { 27 | "name": "stdout", 28 | "output_type": "stream", 29 | "text": [ 30 | "ID: 139698059302928\n", 31 | "Type: \n", 32 | "Value: This is a String\n" 33 | ] 34 | } 35 | ], 36 | "source": [ 37 | "new_string = \"This is a String\" # storing a string\n", 38 | "\n", 39 | "print('ID:', id(new_string)) # shows the object identifier (address)\n", 40 | "print('Type:', type(new_string)) # shows the object type\n", 41 | "print('Value:', new_string) # shows the object value" 42 | ] 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "metadata": { 47 | "colab_type": "text", 48 | "id": "T5KxUoDuBnn_" 49 | }, 50 | "source": [ 51 | "### Simple String" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": 2, 57 | "metadata": { 58 | "colab": { 59 | "base_uri": "https://localhost:8080/", 60 | "height": 34 61 | }, 62 | "colab_type": "code", 63 | "id": "B4qW_qn3BnoA", 64 | "outputId": "47dd2a15-6d61-434c-b916-7238a6cd0766" 65 | }, 66 | "outputs": [ 67 | { 68 | "name": "stdout", 69 | "output_type": "stream", 70 | "text": [ 71 | "Hello! I'm a simple string\n" 72 | ] 73 | } 74 | ], 75 | "source": [ 76 | "simple_string = 'Hello!' + \" I'm a simple string\"\n", 77 | "print(simple_string)" 78 | ] 79 | }, 80 | { 81 | "cell_type": "markdown", 82 | "metadata": { 83 | "colab_type": "text", 84 | "id": "HcNigy5hBnoD" 85 | }, 86 | "source": [ 87 | "### Multi-line String" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 3, 93 | "metadata": { 94 | "colab": { 95 | "base_uri": "https://localhost:8080/", 96 | "height": 34 97 | }, 98 | "colab_type": "code", 99 | "id": "l-NwFKzNBnoE", 100 | "outputId": "07118dff-fd08-4fa7-a037-611e7284b498" 101 | }, 102 | "outputs": [ 103 | { 104 | "data": { 105 | "text/plain": [ 106 | "\"Hello I'm\\na multi-line\\nstring!\"" 107 | ] 108 | }, 109 | "execution_count": 3, 110 | "metadata": { 111 | "tags": [] 112 | }, 113 | "output_type": "execute_result" 114 | } 115 | ], 116 | "source": [ 117 | "# Note the \\n (newline) escape character automatically created\n", 118 | "multi_line_string = \"\"\"Hello I'm\n", 119 | "a multi-line\n", 120 | "string!\"\"\"\n", 121 | "\n", 122 | "multi_line_string" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": 4, 128 | "metadata": { 129 | "colab": { 130 | "base_uri": "https://localhost:8080/", 131 | "height": 67 132 | }, 133 | "colab_type": "code", 134 | "id": "JsNFnvICBnoH", 135 | "outputId": "acd212bc-999b-4583-d555-0bac006cc932" 136 | }, 137 | "outputs": [ 138 | { 139 | "name": "stdout", 140 | "output_type": "stream", 141 | "text": [ 142 | "Hello I'm\n", 143 | "a multi-line\n", 144 | "string!\n" 145 | ] 146 | } 147 | ], 148 | "source": [ 149 | "print(multi_line_string)" 150 | ] 151 | }, 152 | { 153 | "cell_type": "markdown", 154 | "metadata": { 155 | "colab_type": "text", 156 | "id": "KjlmaX9GBnoQ" 157 | }, 158 | "source": [ 159 | "### Unicode literals" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": 7, 165 | "metadata": { 166 | "colab": { 167 | "base_uri": "https://localhost:8080/", 168 | "height": 34 169 | }, 170 | "colab_type": "code", 171 | "id": "eoNe9SntBnoR", 172 | "outputId": "e0a45e2a-139c-44b2-9783-8b11659fe1e2" 173 | }, 174 | "outputs": [ 175 | { 176 | "name": "stdout", 177 | "output_type": "stream", 178 | "text": [ 179 | "Hèllo!\n" 180 | ] 181 | } 182 | ], 183 | "source": [ 184 | "# unicode string literals\n", 185 | "string_with_unicode = 'H\\u00e8llo!'\n", 186 | "print(string_with_unicode)" 187 | ] 188 | }, 189 | { 190 | "cell_type": "code", 191 | "execution_count": 8, 192 | "metadata": { 193 | "colab": { 194 | "base_uri": "https://localhost:8080/", 195 | "height": 34 196 | }, 197 | "colab_type": "code", 198 | "id": "Q-HpqzZlBnoT", 199 | "outputId": "df8a2393-c87e-4d36-cd39-40c945530a7c" 200 | }, 201 | "outputs": [ 202 | { 203 | "name": "stdout", 204 | "output_type": "stream", 205 | "text": [ 206 | "I love Pizza 🍕! Shall we book a cab 🚕 to get pizza?\n" 207 | ] 208 | } 209 | ], 210 | "source": [ 211 | "more_unicode = 'I love Pizza 🍕! Shall we book a cab 🚕 to get pizza?'\n", 212 | "print(more_unicode)" 213 | ] 214 | }, 215 | { 216 | "cell_type": "markdown", 217 | "metadata": { 218 | "colab_type": "text", 219 | "id": "Jo-rCTeyBnoV" 220 | }, 221 | "source": [ 222 | "## Your Turn: How can we reverse the above string?" 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": 9, 228 | "metadata": { 229 | "colab": { 230 | "base_uri": "https://localhost:8080/", 231 | "height": 34 232 | }, 233 | "colab_type": "code", 234 | "id": "1JTtNnSdBnoW", 235 | "outputId": "abe4f9e7-3544-4980-f0c1-5e244974aabd" 236 | }, 237 | "outputs": [ 238 | { 239 | "data": { 240 | "text/plain": [ 241 | "'?azzip teg ot 🚕 bac a koob ew llahS !🍕 azziP evol I'" 242 | ] 243 | }, 244 | "execution_count": 9, 245 | "metadata": { 246 | "tags": [] 247 | }, 248 | "output_type": "execute_result" 249 | } 250 | ], 251 | "source": [ 252 | "more_unicode[::-1] # reverses the string" 253 | ] 254 | }, 255 | { 256 | "cell_type": "markdown", 257 | "metadata": { 258 | "colab_type": "text", 259 | "id": "nk9M4gOABnoY" 260 | }, 261 | "source": [ 262 | "# String Operations\n" 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "metadata": { 268 | "colab_type": "text", 269 | "id": "wkv1vn9WBnoZ" 270 | }, 271 | "source": [ 272 | "### String Concatenation" 273 | ] 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": 10, 278 | "metadata": { 279 | "colab": { 280 | "base_uri": "https://localhost:8080/", 281 | "height": 34 282 | }, 283 | "colab_type": "code", 284 | "id": "lMk0OqhzBnoZ", 285 | "outputId": "a4eeac33-e8ad-490f-bcf5-2e5f27156b51", 286 | "scrolled": true 287 | }, 288 | "outputs": [ 289 | { 290 | "data": { 291 | "text/plain": [ 292 | "'Hello 😊 and welcome to Python 🐍!'" 293 | ] 294 | }, 295 | "execution_count": 10, 296 | "metadata": { 297 | "tags": [] 298 | }, 299 | "output_type": "execute_result" 300 | } 301 | ], 302 | "source": [ 303 | "'Hello 😊' + ' and welcome ' + 'to Python 🐍!'" 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": 11, 309 | "metadata": { 310 | "colab": { 311 | "base_uri": "https://localhost:8080/", 312 | "height": 34 313 | }, 314 | "colab_type": "code", 315 | "id": "_sCOQrlgBnob", 316 | "outputId": "ac233334-e6de-4d57-829a-8c57482bdb84" 317 | }, 318 | "outputs": [ 319 | { 320 | "data": { 321 | "text/plain": [ 322 | "'Hello 😊 and welcome to Python 🐍!'" 323 | ] 324 | }, 325 | "execution_count": 11, 326 | "metadata": { 327 | "tags": [] 328 | }, 329 | "output_type": "execute_result" 330 | } 331 | ], 332 | "source": [ 333 | "'Hello 😊' ' and welcome ' 'to Python 🐍!'" 334 | ] 335 | }, 336 | { 337 | "cell_type": "code", 338 | "execution_count": 12, 339 | "metadata": { 340 | "colab": { 341 | "base_uri": "https://localhost:8080/", 342 | "height": 34 343 | }, 344 | "colab_type": "code", 345 | "id": "iE0EPx8oBnod", 346 | "outputId": "2967c1f3-f644-4f7f-ad15-6f078da69a22" 347 | }, 348 | "outputs": [ 349 | { 350 | "data": { 351 | "text/plain": [ 352 | "'This is another way to concatenate several strings!'" 353 | ] 354 | }, 355 | "execution_count": 12, 356 | "metadata": { 357 | "tags": [] 358 | }, 359 | "output_type": "execute_result" 360 | } 361 | ], 362 | "source": [ 363 | "s3 = ('This '\n", 364 | " 'is another way '\n", 365 | " 'to concatenate '\n", 366 | " 'several strings!')\n", 367 | "s3" 368 | ] 369 | }, 370 | { 371 | "cell_type": "markdown", 372 | "metadata": { 373 | "colab_type": "text", 374 | "id": "884wlesEBnof" 375 | }, 376 | "source": [ 377 | "### Substring check" 378 | ] 379 | }, 380 | { 381 | "cell_type": "code", 382 | "execution_count": 13, 383 | "metadata": { 384 | "colab": { 385 | "base_uri": "https://localhost:8080/", 386 | "height": 34 387 | }, 388 | "colab_type": "code", 389 | "id": "87I7tyrrBnog", 390 | "outputId": "7a811df6-3ed5-4bbd-f0aa-be47dcb5f944" 391 | }, 392 | "outputs": [ 393 | { 394 | "data": { 395 | "text/plain": [ 396 | "True" 397 | ] 398 | }, 399 | "execution_count": 13, 400 | "metadata": { 401 | "tags": [] 402 | }, 403 | "output_type": "execute_result" 404 | } 405 | ], 406 | "source": [ 407 | "'way' in s3" 408 | ] 409 | }, 410 | { 411 | "cell_type": "code", 412 | "execution_count": 14, 413 | "metadata": { 414 | "colab": { 415 | "base_uri": "https://localhost:8080/", 416 | "height": 34 417 | }, 418 | "colab_type": "code", 419 | "id": "EAYQh7ceBnoj", 420 | "outputId": "6d84b8e9-8f44-4a10-e3b2-a3a41b75eadd" 421 | }, 422 | "outputs": [ 423 | { 424 | "data": { 425 | "text/plain": [ 426 | "True" 427 | ] 428 | }, 429 | "execution_count": 14, 430 | "metadata": { 431 | "tags": [] 432 | }, 433 | "output_type": "execute_result" 434 | } 435 | ], 436 | "source": [ 437 | "'python' not in s3" 438 | ] 439 | }, 440 | { 441 | "cell_type": "markdown", 442 | "metadata": { 443 | "colab_type": "text", 444 | "id": "IoEQQXejBnol" 445 | }, 446 | "source": [ 447 | "### String Length" 448 | ] 449 | }, 450 | { 451 | "cell_type": "code", 452 | "execution_count": 15, 453 | "metadata": { 454 | "colab": { 455 | "base_uri": "https://localhost:8080/", 456 | "height": 34 457 | }, 458 | "colab_type": "code", 459 | "id": "8Rabvru9Bnom", 460 | "outputId": "69c706db-0df7-4db0-eedd-b43a7b8539f9" 461 | }, 462 | "outputs": [ 463 | { 464 | "data": { 465 | "text/plain": [ 466 | "51" 467 | ] 468 | }, 469 | "execution_count": 15, 470 | "metadata": { 471 | "tags": [] 472 | }, 473 | "output_type": "execute_result" 474 | } 475 | ], 476 | "source": [ 477 | "len(s3)" 478 | ] 479 | }, 480 | { 481 | "cell_type": "markdown", 482 | "metadata": { 483 | "colab_type": "text", 484 | "id": "9HjoG1o1Bnoq" 485 | }, 486 | "source": [ 487 | "# String Indexing and Slicing" 488 | ] 489 | }, 490 | { 491 | "cell_type": "code", 492 | "execution_count": 16, 493 | "metadata": { 494 | "colab": { 495 | "base_uri": "https://localhost:8080/", 496 | "height": 34 497 | }, 498 | "colab_type": "code", 499 | "id": "KkWd9whbBnos", 500 | "outputId": "805c3947-61c1-402b-ee25-9634e7f0dc19" 501 | }, 502 | "outputs": [ 503 | { 504 | "data": { 505 | "text/plain": [ 506 | "('PYTHON', str)" 507 | ] 508 | }, 509 | "execution_count": 16, 510 | "metadata": { 511 | "tags": [] 512 | }, 513 | "output_type": "execute_result" 514 | } 515 | ], 516 | "source": [ 517 | "# creating a string\n", 518 | "s = 'PYTHON'\n", 519 | "s, type(s)" 520 | ] 521 | }, 522 | { 523 | "cell_type": "markdown", 524 | "metadata": { 525 | "colab_type": "text", 526 | "id": "rEoPiQI_Bnow" 527 | }, 528 | "source": [ 529 | "## String Indexing" 530 | ] 531 | }, 532 | { 533 | "cell_type": "code", 534 | "execution_count": 17, 535 | "metadata": { 536 | "colab": { 537 | "base_uri": "https://localhost:8080/", 538 | "height": 118 539 | }, 540 | "colab_type": "code", 541 | "id": "R2p1jSB2Bnox", 542 | "outputId": "5436869b-1e2d-4d66-cb98-c52c55f0ce52" 543 | }, 544 | "outputs": [ 545 | { 546 | "name": "stdout", 547 | "output_type": "stream", 548 | "text": [ 549 | "Character -> P has index-> 0\n", 550 | "Character -> Y has index-> 1\n", 551 | "Character -> T has index-> 2\n", 552 | "Character -> H has index-> 3\n", 553 | "Character -> O has index-> 4\n", 554 | "Character -> N has index-> 5\n" 555 | ] 556 | } 557 | ], 558 | "source": [ 559 | "# depicting string indexes\n", 560 | "for index, character in enumerate(s):\n", 561 | " print('Character ->', character, 'has index->', index)" 562 | ] 563 | }, 564 | { 565 | "cell_type": "code", 566 | "execution_count": 18, 567 | "metadata": { 568 | "colab": { 569 | "base_uri": "https://localhost:8080/", 570 | "height": 34 571 | }, 572 | "colab_type": "code", 573 | "id": "P-THxKNNBnoz", 574 | "outputId": "5a67aa6d-a483-4d96-a884-b54eb1084250" 575 | }, 576 | "outputs": [ 577 | { 578 | "data": { 579 | "text/plain": [ 580 | "('P', 'Y', 'T', 'H', 'O', 'N')" 581 | ] 582 | }, 583 | "execution_count": 18, 584 | "metadata": { 585 | "tags": [] 586 | }, 587 | "output_type": "execute_result" 588 | } 589 | ], 590 | "source": [ 591 | "s[0], s[1], s[2], s[3], s[4], s[5]" 592 | ] 593 | }, 594 | { 595 | "cell_type": "code", 596 | "execution_count": 19, 597 | "metadata": { 598 | "colab": { 599 | "base_uri": "https://localhost:8080/", 600 | "height": 34 601 | }, 602 | "colab_type": "code", 603 | "id": "rth3BkVDBno1", 604 | "outputId": "3a20a7d0-9bed-4500-bf0a-d1866200796f" 605 | }, 606 | "outputs": [ 607 | { 608 | "data": { 609 | "text/plain": [ 610 | "('N', 'O', 'H', 'T', 'Y', 'P')" 611 | ] 612 | }, 613 | "execution_count": 19, 614 | "metadata": { 615 | "tags": [] 616 | }, 617 | "output_type": "execute_result" 618 | } 619 | ], 620 | "source": [ 621 | "s[-1], s[-2], s[-3], s[-4], s[-5], s[-6]" 622 | ] 623 | }, 624 | { 625 | "cell_type": "markdown", 626 | "metadata": { 627 | "colab_type": "text", 628 | "id": "orsQWfXzBno3" 629 | }, 630 | "source": [ 631 | "## String Slicing" 632 | ] 633 | }, 634 | { 635 | "cell_type": "code", 636 | "execution_count": 20, 637 | "metadata": { 638 | "colab": { 639 | "base_uri": "https://localhost:8080/", 640 | "height": 34 641 | }, 642 | "colab_type": "code", 643 | "id": "PyopofafBno4", 644 | "outputId": "19422e4d-f8ac-4543-936c-2959b789f54c" 645 | }, 646 | "outputs": [ 647 | { 648 | "data": { 649 | "text/plain": [ 650 | "'PYTHON'" 651 | ] 652 | }, 653 | "execution_count": 20, 654 | "metadata": { 655 | "tags": [] 656 | }, 657 | "output_type": "execute_result" 658 | } 659 | ], 660 | "source": [ 661 | "s[:] " 662 | ] 663 | }, 664 | { 665 | "cell_type": "code", 666 | "execution_count": 21, 667 | "metadata": { 668 | "colab": { 669 | "base_uri": "https://localhost:8080/", 670 | "height": 34 671 | }, 672 | "colab_type": "code", 673 | "id": "fE5PWH0sBno5", 674 | "outputId": "b9d0c3b6-c09c-4f2d-818d-8ff1aac43cfb" 675 | }, 676 | "outputs": [ 677 | { 678 | "data": { 679 | "text/plain": [ 680 | "'YTH'" 681 | ] 682 | }, 683 | "execution_count": 21, 684 | "metadata": { 685 | "tags": [] 686 | }, 687 | "output_type": "execute_result" 688 | } 689 | ], 690 | "source": [ 691 | "s[1:4]" 692 | ] 693 | }, 694 | { 695 | "cell_type": "code", 696 | "execution_count": 22, 697 | "metadata": { 698 | "colab": { 699 | "base_uri": "https://localhost:8080/", 700 | "height": 34 701 | }, 702 | "colab_type": "code", 703 | "id": "wvX62d3QBno7", 704 | "outputId": "3f7a6b03-c87c-4333-cf95-e4570de263af" 705 | }, 706 | "outputs": [ 707 | { 708 | "data": { 709 | "text/plain": [ 710 | "('PYT', 'HON')" 711 | ] 712 | }, 713 | "execution_count": 22, 714 | "metadata": { 715 | "tags": [] 716 | }, 717 | "output_type": "execute_result" 718 | } 719 | ], 720 | "source": [ 721 | "s[:3], s[3:]" 722 | ] 723 | }, 724 | { 725 | "cell_type": "markdown", 726 | "metadata": { 727 | "colab_type": "text", 728 | "id": "cmKwoIr8BnpF" 729 | }, 730 | "source": [ 731 | "## String slicing with offsets" 732 | ] 733 | }, 734 | { 735 | "cell_type": "code", 736 | "execution_count": 23, 737 | "metadata": { 738 | "colab": { 739 | "base_uri": "https://localhost:8080/", 740 | "height": 34 741 | }, 742 | "colab_type": "code", 743 | "id": "34rGic5pBnpG", 744 | "outputId": "8dbdf5af-2b33-43a8-e2e0-ef646322ee5a" 745 | }, 746 | "outputs": [ 747 | { 748 | "data": { 749 | "text/plain": [ 750 | "'PYTHON'" 751 | ] 752 | }, 753 | "execution_count": 23, 754 | "metadata": { 755 | "tags": [] 756 | }, 757 | "output_type": "execute_result" 758 | } 759 | ], 760 | "source": [ 761 | "s[::1] # no offset" 762 | ] 763 | }, 764 | { 765 | "cell_type": "code", 766 | "execution_count": 24, 767 | "metadata": { 768 | "colab": { 769 | "base_uri": "https://localhost:8080/", 770 | "height": 34 771 | }, 772 | "colab_type": "code", 773 | "id": "rxOPr3m6BnpL", 774 | "outputId": "426c5b8c-0b99-4b1a-8cc0-e1f73b9c5c46" 775 | }, 776 | "outputs": [ 777 | { 778 | "data": { 779 | "text/plain": [ 780 | "'PTO'" 781 | ] 782 | }, 783 | "execution_count": 24, 784 | "metadata": { 785 | "tags": [] 786 | }, 787 | "output_type": "execute_result" 788 | } 789 | ], 790 | "source": [ 791 | "s[::2] # print every 2nd character in string" 792 | ] 793 | }, 794 | { 795 | "cell_type": "markdown", 796 | "metadata": { 797 | "colab_type": "text", 798 | "id": "b105ZcfyBnpN" 799 | }, 800 | "source": [ 801 | "# String Immutability" 802 | ] 803 | }, 804 | { 805 | "cell_type": "code", 806 | "execution_count": 26, 807 | "metadata": { 808 | "colab": { 809 | "base_uri": "https://localhost:8080/", 810 | "height": 178 811 | }, 812 | "colab_type": "code", 813 | "id": "HGYPZGsABnpO", 814 | "outputId": "979ad4fd-8e94-46e1-f7c8-f3ee9a7bfe1f" 815 | }, 816 | "outputs": [ 817 | { 818 | "ename": "TypeError", 819 | "evalue": "ignored", 820 | "output_type": "error", 821 | "traceback": [ 822 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 823 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 824 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# strings are immutable hence assignment throws error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0ms\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'X'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 825 | "\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment" 826 | ] 827 | } 828 | ], 829 | "source": [ 830 | "# strings are immutable hence assignment throws error\n", 831 | "s[0] = 'X'" 832 | ] 833 | }, 834 | { 835 | "cell_type": "code", 836 | "execution_count": 27, 837 | "metadata": { 838 | "colab": { 839 | "base_uri": "https://localhost:8080/", 840 | "height": 67 841 | }, 842 | "colab_type": "code", 843 | "id": "jgrSZyDtBnpP", 844 | "outputId": "4ef3554b-b4da-4c4d-d517-76d480852d05" 845 | }, 846 | "outputs": [ 847 | { 848 | "name": "stdout", 849 | "output_type": "stream", 850 | "text": [ 851 | "Original String id: 139698623376440\n", 852 | "XYTHON\n", 853 | "New String id: 139698050130024\n" 854 | ] 855 | } 856 | ], 857 | "source": [ 858 | "print('Original String id:', id(s))\n", 859 | "# creates a new string\n", 860 | "s = 'X' + s[1:]\n", 861 | "print(s)\n", 862 | "print('New String id:', id(s))" 863 | ] 864 | }, 865 | { 866 | "cell_type": "markdown", 867 | "metadata": { 868 | "colab_type": "text", 869 | "id": "dyiL0QiEBnpR" 870 | }, 871 | "source": [ 872 | "# Useful String methods" 873 | ] 874 | }, 875 | { 876 | "cell_type": "markdown", 877 | "metadata": { 878 | "colab_type": "text", 879 | "id": "NVMPBDSXBnpS" 880 | }, 881 | "source": [ 882 | "## Case Conversions" 883 | ] 884 | }, 885 | { 886 | "cell_type": "code", 887 | "execution_count": 0, 888 | "metadata": { 889 | "colab": {}, 890 | "colab_type": "code", 891 | "id": "5FgTAV4TBnpS" 892 | }, 893 | "outputs": [], 894 | "source": [ 895 | "s = 'python is great'" 896 | ] 897 | }, 898 | { 899 | "cell_type": "code", 900 | "execution_count": 29, 901 | "metadata": { 902 | "colab": { 903 | "base_uri": "https://localhost:8080/", 904 | "height": 34 905 | }, 906 | "colab_type": "code", 907 | "id": "BtEaTNUKBnpV", 908 | "outputId": "a22cce4b-125f-4b75-de4a-8b0e0c8cd51a" 909 | }, 910 | "outputs": [ 911 | { 912 | "data": { 913 | "text/plain": [ 914 | "'Python is great'" 915 | ] 916 | }, 917 | "execution_count": 29, 918 | "metadata": { 919 | "tags": [] 920 | }, 921 | "output_type": "execute_result" 922 | } 923 | ], 924 | "source": [ 925 | "s.capitalize()" 926 | ] 927 | }, 928 | { 929 | "cell_type": "code", 930 | "execution_count": 30, 931 | "metadata": { 932 | "colab": { 933 | "base_uri": "https://localhost:8080/", 934 | "height": 34 935 | }, 936 | "colab_type": "code", 937 | "id": "O0CnwA3OBnpY", 938 | "outputId": "eacb7086-8869-474a-dc37-497cdc751721" 939 | }, 940 | "outputs": [ 941 | { 942 | "data": { 943 | "text/plain": [ 944 | "'PYTHON IS GREAT'" 945 | ] 946 | }, 947 | "execution_count": 30, 948 | "metadata": { 949 | "tags": [] 950 | }, 951 | "output_type": "execute_result" 952 | } 953 | ], 954 | "source": [ 955 | "s.upper()" 956 | ] 957 | }, 958 | { 959 | "cell_type": "code", 960 | "execution_count": 31, 961 | "metadata": { 962 | "colab": { 963 | "base_uri": "https://localhost:8080/", 964 | "height": 34 965 | }, 966 | "colab_type": "code", 967 | "id": "saCVI_vgBnpb", 968 | "outputId": "f12e3930-4bad-4134-af0c-e4db64503a2d" 969 | }, 970 | "outputs": [ 971 | { 972 | "data": { 973 | "text/plain": [ 974 | "'Python Is Great'" 975 | ] 976 | }, 977 | "execution_count": 31, 978 | "metadata": { 979 | "tags": [] 980 | }, 981 | "output_type": "execute_result" 982 | } 983 | ], 984 | "source": [ 985 | "s.title()" 986 | ] 987 | }, 988 | { 989 | "cell_type": "markdown", 990 | "metadata": { 991 | "colab_type": "text", 992 | "id": "dEIDbD-GBnpd" 993 | }, 994 | "source": [ 995 | "## String Replace" 996 | ] 997 | }, 998 | { 999 | "cell_type": "code", 1000 | "execution_count": 32, 1001 | "metadata": { 1002 | "colab": { 1003 | "base_uri": "https://localhost:8080/", 1004 | "height": 34 1005 | }, 1006 | "colab_type": "code", 1007 | "id": "6WZvrBIZBnpe", 1008 | "outputId": "531f7b50-3f00-4c06-f555-a887221cf9ac" 1009 | }, 1010 | "outputs": [ 1011 | { 1012 | "data": { 1013 | "text/plain": [ 1014 | "'NLP is great'" 1015 | ] 1016 | }, 1017 | "execution_count": 32, 1018 | "metadata": { 1019 | "tags": [] 1020 | }, 1021 | "output_type": "execute_result" 1022 | } 1023 | ], 1024 | "source": [ 1025 | "s.replace('python', 'NLP')" 1026 | ] 1027 | }, 1028 | { 1029 | "cell_type": "markdown", 1030 | "metadata": { 1031 | "colab_type": "text", 1032 | "id": "KZn6-Ht1Bnpg" 1033 | }, 1034 | "source": [ 1035 | "## Numeric Checks" 1036 | ] 1037 | }, 1038 | { 1039 | "cell_type": "code", 1040 | "execution_count": 33, 1041 | "metadata": { 1042 | "colab": { 1043 | "base_uri": "https://localhost:8080/", 1044 | "height": 34 1045 | }, 1046 | "colab_type": "code", 1047 | "id": "0tUUPE1dBnph", 1048 | "outputId": "898684bf-f5e3-490a-8f7d-8cb926f6bb2c" 1049 | }, 1050 | "outputs": [ 1051 | { 1052 | "data": { 1053 | "text/plain": [ 1054 | "True" 1055 | ] 1056 | }, 1057 | "execution_count": 33, 1058 | "metadata": { 1059 | "tags": [] 1060 | }, 1061 | "output_type": "execute_result" 1062 | } 1063 | ], 1064 | "source": [ 1065 | "'12345'.isdecimal()" 1066 | ] 1067 | }, 1068 | { 1069 | "cell_type": "code", 1070 | "execution_count": 34, 1071 | "metadata": { 1072 | "colab": { 1073 | "base_uri": "https://localhost:8080/", 1074 | "height": 34 1075 | }, 1076 | "colab_type": "code", 1077 | "id": "8FZb9sWmBnpj", 1078 | "outputId": "33d298d2-cdb6-4ee2-bcf0-245c93e46002" 1079 | }, 1080 | "outputs": [ 1081 | { 1082 | "data": { 1083 | "text/plain": [ 1084 | "False" 1085 | ] 1086 | }, 1087 | "execution_count": 34, 1088 | "metadata": { 1089 | "tags": [] 1090 | }, 1091 | "output_type": "execute_result" 1092 | } 1093 | ], 1094 | "source": [ 1095 | "'apollo11'.isdecimal()" 1096 | ] 1097 | }, 1098 | { 1099 | "cell_type": "markdown", 1100 | "metadata": { 1101 | "colab_type": "text", 1102 | "id": "K_0eYIBhBnpp" 1103 | }, 1104 | "source": [ 1105 | "## Alphabet Checks" 1106 | ] 1107 | }, 1108 | { 1109 | "cell_type": "code", 1110 | "execution_count": 35, 1111 | "metadata": { 1112 | "colab": { 1113 | "base_uri": "https://localhost:8080/", 1114 | "height": 34 1115 | }, 1116 | "colab_type": "code", 1117 | "id": "zcsr4dSeBnpp", 1118 | "outputId": "94611a9b-4c5b-4f0d-dabe-665dd511d09a" 1119 | }, 1120 | "outputs": [ 1121 | { 1122 | "data": { 1123 | "text/plain": [ 1124 | "True" 1125 | ] 1126 | }, 1127 | "execution_count": 35, 1128 | "metadata": { 1129 | "tags": [] 1130 | }, 1131 | "output_type": "execute_result" 1132 | } 1133 | ], 1134 | "source": [ 1135 | "'python'.isalpha()" 1136 | ] 1137 | }, 1138 | { 1139 | "cell_type": "code", 1140 | "execution_count": 36, 1141 | "metadata": { 1142 | "colab": { 1143 | "base_uri": "https://localhost:8080/", 1144 | "height": 34 1145 | }, 1146 | "colab_type": "code", 1147 | "id": "dg62LrXwBnps", 1148 | "outputId": "f150d1e2-f0b8-4f34-d369-d27fe19b1faa" 1149 | }, 1150 | "outputs": [ 1151 | { 1152 | "data": { 1153 | "text/plain": [ 1154 | "False" 1155 | ] 1156 | }, 1157 | "execution_count": 36, 1158 | "metadata": { 1159 | "tags": [] 1160 | }, 1161 | "output_type": "execute_result" 1162 | } 1163 | ], 1164 | "source": [ 1165 | "'number1'.isalpha()" 1166 | ] 1167 | }, 1168 | { 1169 | "cell_type": "markdown", 1170 | "metadata": { 1171 | "colab_type": "text", 1172 | "id": "L0VAth3-Bnpv" 1173 | }, 1174 | "source": [ 1175 | "## Alphanumeric Checks" 1176 | ] 1177 | }, 1178 | { 1179 | "cell_type": "code", 1180 | "execution_count": 37, 1181 | "metadata": { 1182 | "colab": { 1183 | "base_uri": "https://localhost:8080/", 1184 | "height": 34 1185 | }, 1186 | "colab_type": "code", 1187 | "id": "cwayE69SBnpw", 1188 | "outputId": "465aab92-3ad1-43da-d18d-26e04278221e" 1189 | }, 1190 | "outputs": [ 1191 | { 1192 | "data": { 1193 | "text/plain": [ 1194 | "True" 1195 | ] 1196 | }, 1197 | "execution_count": 37, 1198 | "metadata": { 1199 | "tags": [] 1200 | }, 1201 | "output_type": "execute_result" 1202 | } 1203 | ], 1204 | "source": [ 1205 | "'total'.isalnum()" 1206 | ] 1207 | }, 1208 | { 1209 | "cell_type": "code", 1210 | "execution_count": 38, 1211 | "metadata": { 1212 | "colab": { 1213 | "base_uri": "https://localhost:8080/", 1214 | "height": 34 1215 | }, 1216 | "colab_type": "code", 1217 | "id": "nnusNFRkBnpz", 1218 | "outputId": "8f417ee8-eb1b-4e4f-ece4-a2d532c62afa" 1219 | }, 1220 | "outputs": [ 1221 | { 1222 | "data": { 1223 | "text/plain": [ 1224 | "True" 1225 | ] 1226 | }, 1227 | "execution_count": 38, 1228 | "metadata": { 1229 | "tags": [] 1230 | }, 1231 | "output_type": "execute_result" 1232 | } 1233 | ], 1234 | "source": [ 1235 | "'abc123'.isalnum()" 1236 | ] 1237 | }, 1238 | { 1239 | "cell_type": "code", 1240 | "execution_count": 39, 1241 | "metadata": { 1242 | "colab": { 1243 | "base_uri": "https://localhost:8080/", 1244 | "height": 34 1245 | }, 1246 | "colab_type": "code", 1247 | "id": "WGB_jtIPBnp5", 1248 | "outputId": "0c8b7377-6312-47af-c7bb-bd79aea7e4da" 1249 | }, 1250 | "outputs": [ 1251 | { 1252 | "data": { 1253 | "text/plain": [ 1254 | "False" 1255 | ] 1256 | }, 1257 | "execution_count": 39, 1258 | "metadata": { 1259 | "tags": [] 1260 | }, 1261 | "output_type": "execute_result" 1262 | } 1263 | ], 1264 | "source": [ 1265 | "'1+1'.isalnum()" 1266 | ] 1267 | }, 1268 | { 1269 | "cell_type": "markdown", 1270 | "metadata": { 1271 | "colab_type": "text", 1272 | "id": "vLZh3XIEBnp9" 1273 | }, 1274 | "source": [ 1275 | "## String splitting and joining" 1276 | ] 1277 | }, 1278 | { 1279 | "cell_type": "code", 1280 | "execution_count": 40, 1281 | "metadata": { 1282 | "colab": { 1283 | "base_uri": "https://localhost:8080/", 1284 | "height": 34 1285 | }, 1286 | "colab_type": "code", 1287 | "id": "exc7DmncBnp-", 1288 | "outputId": "68048efd-05c4-48c3-a5ec-6b5db55dec46" 1289 | }, 1290 | "outputs": [ 1291 | { 1292 | "data": { 1293 | "text/plain": [ 1294 | "'I,am,a,comma,separated,string'" 1295 | ] 1296 | }, 1297 | "execution_count": 40, 1298 | "metadata": { 1299 | "tags": [] 1300 | }, 1301 | "output_type": "execute_result" 1302 | } 1303 | ], 1304 | "source": [ 1305 | "s = 'I,am,a,comma,separated,string'\n", 1306 | "s" 1307 | ] 1308 | }, 1309 | { 1310 | "cell_type": "code", 1311 | "execution_count": 41, 1312 | "metadata": { 1313 | "colab": { 1314 | "base_uri": "https://localhost:8080/", 1315 | "height": 34 1316 | }, 1317 | "colab_type": "code", 1318 | "id": "LHIM7IOsBnqA", 1319 | "outputId": "33ea6840-0f29-4a7c-9248-39b1d5fe59e2" 1320 | }, 1321 | "outputs": [ 1322 | { 1323 | "data": { 1324 | "text/plain": [ 1325 | "['I', 'am', 'a', 'comma', 'separated', 'string']" 1326 | ] 1327 | }, 1328 | "execution_count": 41, 1329 | "metadata": { 1330 | "tags": [] 1331 | }, 1332 | "output_type": "execute_result" 1333 | } 1334 | ], 1335 | "source": [ 1336 | "s.split(',')" 1337 | ] 1338 | }, 1339 | { 1340 | "cell_type": "code", 1341 | "execution_count": 42, 1342 | "metadata": { 1343 | "colab": { 1344 | "base_uri": "https://localhost:8080/", 1345 | "height": 34 1346 | }, 1347 | "colab_type": "code", 1348 | "id": "0QXsIi_dBnqC", 1349 | "outputId": "11c1057e-f853-4afe-94b8-89a47eddd608" 1350 | }, 1351 | "outputs": [ 1352 | { 1353 | "data": { 1354 | "text/plain": [ 1355 | "'I am a comma separated string'" 1356 | ] 1357 | }, 1358 | "execution_count": 42, 1359 | "metadata": { 1360 | "tags": [] 1361 | }, 1362 | "output_type": "execute_result" 1363 | } 1364 | ], 1365 | "source": [ 1366 | "' '.join(s.split(','))" 1367 | ] 1368 | }, 1369 | { 1370 | "cell_type": "code", 1371 | "execution_count": 43, 1372 | "metadata": { 1373 | "colab": { 1374 | "base_uri": "https://localhost:8080/", 1375 | "height": 34 1376 | }, 1377 | "colab_type": "code", 1378 | "id": "Tna3rsoIBnqE", 1379 | "outputId": "a0ba3464-edf6-4b83-9eda-bc5b3cd01bc4" 1380 | }, 1381 | "outputs": [ 1382 | { 1383 | "data": { 1384 | "text/plain": [ 1385 | "' I am surrounded by spaces '" 1386 | ] 1387 | }, 1388 | "execution_count": 43, 1389 | "metadata": { 1390 | "tags": [] 1391 | }, 1392 | "output_type": "execute_result" 1393 | } 1394 | ], 1395 | "source": [ 1396 | "# stripping whitespace characters\n", 1397 | "s = ' I am surrounded by spaces '\n", 1398 | "s" 1399 | ] 1400 | }, 1401 | { 1402 | "cell_type": "code", 1403 | "execution_count": 44, 1404 | "metadata": { 1405 | "colab": { 1406 | "base_uri": "https://localhost:8080/", 1407 | "height": 34 1408 | }, 1409 | "colab_type": "code", 1410 | "id": "cfMRkz-sBnqG", 1411 | "outputId": "0d732555-bc6c-4d71-f808-ded5c8c909b3" 1412 | }, 1413 | "outputs": [ 1414 | { 1415 | "data": { 1416 | "text/plain": [ 1417 | "'I am surrounded by spaces'" 1418 | ] 1419 | }, 1420 | "execution_count": 44, 1421 | "metadata": { 1422 | "tags": [] 1423 | }, 1424 | "output_type": "execute_result" 1425 | } 1426 | ], 1427 | "source": [ 1428 | "s.strip()" 1429 | ] 1430 | }, 1431 | { 1432 | "cell_type": "code", 1433 | "execution_count": 45, 1434 | "metadata": { 1435 | "colab": { 1436 | "base_uri": "https://localhost:8080/", 1437 | "height": 34 1438 | }, 1439 | "colab_type": "code", 1440 | "id": "uILdFoJDBnqJ", 1441 | "outputId": "06fde3c9-0514-4c2c-f03e-84d82adb88c2" 1442 | }, 1443 | "outputs": [ 1444 | { 1445 | "data": { 1446 | "text/plain": [ 1447 | "['Python is great', ' NLP is also good', '']" 1448 | ] 1449 | }, 1450 | "execution_count": 45, 1451 | "metadata": { 1452 | "tags": [] 1453 | }, 1454 | "output_type": "execute_result" 1455 | } 1456 | ], 1457 | "source": [ 1458 | "sentences = 'Python is great. NLP is also good.'\n", 1459 | "sentences.split('.')" 1460 | ] 1461 | }, 1462 | { 1463 | "cell_type": "markdown", 1464 | "metadata": { 1465 | "colab_type": "text", 1466 | "id": "ipWG7jAIBnqP" 1467 | }, 1468 | "source": [ 1469 | "# String formatting" 1470 | ] 1471 | }, 1472 | { 1473 | "cell_type": "markdown", 1474 | "metadata": { 1475 | "colab_type": "text", 1476 | "id": "KlBDy_dfBnqQ" 1477 | }, 1478 | "source": [ 1479 | "## Formatting expressions with different data types - old style" 1480 | ] 1481 | }, 1482 | { 1483 | "cell_type": "code", 1484 | "execution_count": 46, 1485 | "metadata": { 1486 | "colab": { 1487 | "base_uri": "https://localhost:8080/", 1488 | "height": 34 1489 | }, 1490 | "colab_type": "code", 1491 | "id": "loHzxZr2BnqR", 1492 | "outputId": "51736aef-9cc8-4b5a-e7a6-ca7ffb0a7616" 1493 | }, 1494 | "outputs": [ 1495 | { 1496 | "data": { 1497 | "text/plain": [ 1498 | "'We have 2 bottles containing 2.50 gallons of milk'" 1499 | ] 1500 | }, 1501 | "execution_count": 46, 1502 | "metadata": { 1503 | "tags": [] 1504 | }, 1505 | "output_type": "execute_result" 1506 | } 1507 | ], 1508 | "source": [ 1509 | "'We have %d %s containing %.2f gallons of %s' %(2, 'bottles', 2.5, 'milk')" 1510 | ] 1511 | }, 1512 | { 1513 | "cell_type": "code", 1514 | "execution_count": 47, 1515 | "metadata": { 1516 | "colab": { 1517 | "base_uri": "https://localhost:8080/", 1518 | "height": 34 1519 | }, 1520 | "colab_type": "code", 1521 | "id": "dT1oE_fPBnqT", 1522 | "outputId": "003a1424-ff95-4889-e6bc-7f009077855a" 1523 | }, 1524 | "outputs": [ 1525 | { 1526 | "data": { 1527 | "text/plain": [ 1528 | "'We have 5 jugs containing 10.87 gallons of juice'" 1529 | ] 1530 | }, 1531 | "execution_count": 47, 1532 | "metadata": { 1533 | "tags": [] 1534 | }, 1535 | "output_type": "execute_result" 1536 | } 1537 | ], 1538 | "source": [ 1539 | "'We have %d %s containing %.2f gallons of %s' %(5.21, 'jugs', 10.86763, 'juice')" 1540 | ] 1541 | }, 1542 | { 1543 | "cell_type": "markdown", 1544 | "metadata": { 1545 | "colab_type": "text", 1546 | "id": "PMze-THzBnqV" 1547 | }, 1548 | "source": [ 1549 | "## Formatting strings using the format method - new style" 1550 | ] 1551 | }, 1552 | { 1553 | "cell_type": "code", 1554 | "execution_count": 48, 1555 | "metadata": { 1556 | "colab": { 1557 | "base_uri": "https://localhost:8080/", 1558 | "height": 34 1559 | }, 1560 | "colab_type": "code", 1561 | "id": "T0P8sGPLBnqW", 1562 | "outputId": "a52cadf9-73ed-4865-fcd1-a6a29cfedff9" 1563 | }, 1564 | "outputs": [ 1565 | { 1566 | "data": { 1567 | "text/plain": [ 1568 | "'Hello Mr. Jones, it is a great pleasure to meet you at 5'" 1569 | ] 1570 | }, 1571 | "execution_count": 48, 1572 | "metadata": { 1573 | "tags": [] 1574 | }, 1575 | "output_type": "execute_result" 1576 | } 1577 | ], 1578 | "source": [ 1579 | "'Hello {} {}, it is a great {} to meet you at {}'.format('Mr.', 'Jones', 'pleasure', 5)" 1580 | ] 1581 | }, 1582 | { 1583 | "cell_type": "code", 1584 | "execution_count": 49, 1585 | "metadata": { 1586 | "colab": { 1587 | "base_uri": "https://localhost:8080/", 1588 | "height": 34 1589 | }, 1590 | "colab_type": "code", 1591 | "id": "J0JSNJ7kBnqX", 1592 | "outputId": "0b4881c5-7f5f-4a37-b2ed-dd56d77727d2" 1593 | }, 1594 | "outputs": [ 1595 | { 1596 | "data": { 1597 | "text/plain": [ 1598 | "\"Hello Sir Arthur, it is a great honor to meet you at 9 o' clock\"" 1599 | ] 1600 | }, 1601 | "execution_count": 49, 1602 | "metadata": { 1603 | "tags": [] 1604 | }, 1605 | "output_type": "execute_result" 1606 | } 1607 | ], 1608 | "source": [ 1609 | "'Hello {} {}, it is a great {} to meet you at {} o\\' clock'.format('Sir', 'Arthur', 'honor', 9)" 1610 | ] 1611 | }, 1612 | { 1613 | "cell_type": "markdown", 1614 | "metadata": { 1615 | "colab_type": "text", 1616 | "id": "Dk55aNB6Bnqa" 1617 | }, 1618 | "source": [ 1619 | "## Alternative ways of using string format" 1620 | ] 1621 | }, 1622 | { 1623 | "cell_type": "code", 1624 | "execution_count": 50, 1625 | "metadata": { 1626 | "colab": { 1627 | "base_uri": "https://localhost:8080/", 1628 | "height": 34 1629 | }, 1630 | "colab_type": "code", 1631 | "id": "JSnzk2W3Bnqa", 1632 | "outputId": "b1b1aa73-af94-470d-956e-44b889257e01" 1633 | }, 1634 | "outputs": [ 1635 | { 1636 | "data": { 1637 | "text/plain": [ 1638 | "'I have a sandwich and a soda with me'" 1639 | ] 1640 | }, 1641 | "execution_count": 50, 1642 | "metadata": { 1643 | "tags": [] 1644 | }, 1645 | "output_type": "execute_result" 1646 | } 1647 | ], 1648 | "source": [ 1649 | "'I have a {food_item} and a {drink_item} with me'.format(drink_item='soda', food_item='sandwich')" 1650 | ] 1651 | }, 1652 | { 1653 | "cell_type": "code", 1654 | "execution_count": 51, 1655 | "metadata": { 1656 | "colab": { 1657 | "base_uri": "https://localhost:8080/", 1658 | "height": 34 1659 | }, 1660 | "colab_type": "code", 1661 | "id": "WxSvcEhRBnqc", 1662 | "outputId": "794837e3-877b-4709-832d-2272686b2413" 1663 | }, 1664 | "outputs": [ 1665 | { 1666 | "data": { 1667 | "text/plain": [ 1668 | "\"The dog has the following attributes: ['lazy', 'loyal']\"" 1669 | ] 1670 | }, 1671 | "execution_count": 51, 1672 | "metadata": { 1673 | "tags": [] 1674 | }, 1675 | "output_type": "execute_result" 1676 | } 1677 | ], 1678 | "source": [ 1679 | "'The {animal} has the following attributes: {attributes}'.format(animal='dog', attributes=['lazy', 'loyal'])" 1680 | ] 1681 | }, 1682 | { 1683 | "cell_type": "markdown", 1684 | "metadata": { 1685 | "colab_type": "text", 1686 | "id": "-btesgo3Bnqe" 1687 | }, 1688 | "source": [ 1689 | "# Regular Expressions" 1690 | ] 1691 | }, 1692 | { 1693 | "cell_type": "code", 1694 | "execution_count": 0, 1695 | "metadata": { 1696 | "colab": {}, 1697 | "colab_type": "code", 1698 | "id": "ynyaFmfoBnqf" 1699 | }, 1700 | "outputs": [], 1701 | "source": [ 1702 | "s1 = 'Python is an excellent language'\n", 1703 | "s2 = 'I love the Python language. I also use Python to build applications at work!'" 1704 | ] 1705 | }, 1706 | { 1707 | "cell_type": "code", 1708 | "execution_count": 0, 1709 | "metadata": { 1710 | "colab": {}, 1711 | "colab_type": "code", 1712 | "id": "n_XPqHFpBnqh" 1713 | }, 1714 | "outputs": [], 1715 | "source": [ 1716 | "import re\n", 1717 | "\n", 1718 | "pattern = 'python'\n", 1719 | "# match only returns a match if regex match is found at the beginning of the string\n", 1720 | "re.match(pattern, s1)" 1721 | ] 1722 | }, 1723 | { 1724 | "cell_type": "code", 1725 | "execution_count": 54, 1726 | "metadata": { 1727 | "colab": { 1728 | "base_uri": "https://localhost:8080/", 1729 | "height": 34 1730 | }, 1731 | "colab_type": "code", 1732 | "id": "9V6dcymaBnqi", 1733 | "outputId": "8345b3f6-c244-4b9e-b333-2ec9fb15b5c0" 1734 | }, 1735 | "outputs": [ 1736 | { 1737 | "data": { 1738 | "text/plain": [ 1739 | "<_sre.SRE_Match object; span=(0, 6), match='Python'>" 1740 | ] 1741 | }, 1742 | "execution_count": 54, 1743 | "metadata": { 1744 | "tags": [] 1745 | }, 1746 | "output_type": "execute_result" 1747 | } 1748 | ], 1749 | "source": [ 1750 | "# pattern is in lower case hence ignore case flag helps\n", 1751 | "# in matching same pattern with different cases\n", 1752 | "re.match(pattern, s1, flags=re.IGNORECASE)" 1753 | ] 1754 | }, 1755 | { 1756 | "cell_type": "code", 1757 | "execution_count": 55, 1758 | "metadata": { 1759 | "colab": { 1760 | "base_uri": "https://localhost:8080/", 1761 | "height": 34 1762 | }, 1763 | "colab_type": "code", 1764 | "id": "hqhkTjMFBnqn", 1765 | "outputId": "4d880b8c-66be-437b-e007-e401cddf3a99" 1766 | }, 1767 | "outputs": [ 1768 | { 1769 | "name": "stdout", 1770 | "output_type": "stream", 1771 | "text": [ 1772 | "Found match Python ranging from index 0 - 6 in the string \"Python is an excellent language\"\n" 1773 | ] 1774 | } 1775 | ], 1776 | "source": [ 1777 | "# printing matched string and its indices in the original string\n", 1778 | "m = re.match(pattern, s1, flags=re.IGNORECASE)\n", 1779 | "print('Found match {} ranging from index {} - {} in the string \"{}\"'.format(m.group(0), \n", 1780 | " m.start(), \n", 1781 | " m.end(), s1))" 1782 | ] 1783 | }, 1784 | { 1785 | "cell_type": "code", 1786 | "execution_count": 0, 1787 | "metadata": { 1788 | "colab": {}, 1789 | "colab_type": "code", 1790 | "id": "C3ZCmkutBnqo" 1791 | }, 1792 | "outputs": [], 1793 | "source": [ 1794 | "# match does not work when pattern is not there in the beginning of string s2\n", 1795 | "re.match(pattern, s2, re.IGNORECASE)" 1796 | ] 1797 | }, 1798 | { 1799 | "cell_type": "code", 1800 | "execution_count": 57, 1801 | "metadata": { 1802 | "colab": { 1803 | "base_uri": "https://localhost:8080/", 1804 | "height": 34 1805 | }, 1806 | "colab_type": "code", 1807 | "id": "RbpdhXBuBnqq", 1808 | "outputId": "a5cd6f40-f3c5-4acb-c315-16fdfd77715c" 1809 | }, 1810 | "outputs": [ 1811 | { 1812 | "data": { 1813 | "text/plain": [ 1814 | "<_sre.SRE_Match object; span=(11, 17), match='Python'>" 1815 | ] 1816 | }, 1817 | "execution_count": 57, 1818 | "metadata": { 1819 | "tags": [] 1820 | }, 1821 | "output_type": "execute_result" 1822 | } 1823 | ], 1824 | "source": [ 1825 | "# illustrating find and search methods using the re module\n", 1826 | "re.search(pattern, s2, re.IGNORECASE)" 1827 | ] 1828 | }, 1829 | { 1830 | "cell_type": "code", 1831 | "execution_count": 58, 1832 | "metadata": { 1833 | "colab": { 1834 | "base_uri": "https://localhost:8080/", 1835 | "height": 34 1836 | }, 1837 | "colab_type": "code", 1838 | "id": "FPVDILoEBnqs", 1839 | "outputId": "6b267470-47c8-4f90-abeb-c4343a28184e" 1840 | }, 1841 | "outputs": [ 1842 | { 1843 | "data": { 1844 | "text/plain": [ 1845 | "['Python', 'Python']" 1846 | ] 1847 | }, 1848 | "execution_count": 58, 1849 | "metadata": { 1850 | "tags": [] 1851 | }, 1852 | "output_type": "execute_result" 1853 | } 1854 | ], 1855 | "source": [ 1856 | "re.findall(pattern, s2, re.IGNORECASE)" 1857 | ] 1858 | }, 1859 | { 1860 | "cell_type": "code", 1861 | "execution_count": 59, 1862 | "metadata": { 1863 | "colab": { 1864 | "base_uri": "https://localhost:8080/", 1865 | "height": 34 1866 | }, 1867 | "colab_type": "code", 1868 | "id": "_0ctBnc9Bnqw", 1869 | "outputId": "88203b24-7010-436b-c4b9-3af31cbaed3d" 1870 | }, 1871 | "outputs": [ 1872 | { 1873 | "data": { 1874 | "text/plain": [ 1875 | "" 1876 | ] 1877 | }, 1878 | "execution_count": 59, 1879 | "metadata": { 1880 | "tags": [] 1881 | }, 1882 | "output_type": "execute_result" 1883 | } 1884 | ], 1885 | "source": [ 1886 | "match_objs = re.finditer(pattern, s2, re.IGNORECASE)\n", 1887 | "match_objs" 1888 | ] 1889 | }, 1890 | { 1891 | "cell_type": "code", 1892 | "execution_count": 60, 1893 | "metadata": { 1894 | "colab": { 1895 | "base_uri": "https://localhost:8080/", 1896 | "height": 67 1897 | }, 1898 | "colab_type": "code", 1899 | "id": "nCLXMMU8Bnqy", 1900 | "outputId": "d8fe89af-7bc3-44af-a6ca-d63f9a166249" 1901 | }, 1902 | "outputs": [ 1903 | { 1904 | "name": "stdout", 1905 | "output_type": "stream", 1906 | "text": [ 1907 | "String: I love the Python language. I also use Python to build applications at work!\n", 1908 | "Found match \"Python\" ranging from index 11 - 17\n", 1909 | "Found match \"Python\" ranging from index 39 - 45\n" 1910 | ] 1911 | } 1912 | ], 1913 | "source": [ 1914 | "print(\"String:\", s2)\n", 1915 | "for m in match_objs:\n", 1916 | " print('Found match \"{}\" ranging from index {} - {}'.format(m.group(0), \n", 1917 | " m.start(), m.end()))" 1918 | ] 1919 | }, 1920 | { 1921 | "cell_type": "code", 1922 | "execution_count": 61, 1923 | "metadata": { 1924 | "colab": { 1925 | "base_uri": "https://localhost:8080/", 1926 | "height": 34 1927 | }, 1928 | "colab_type": "code", 1929 | "id": "B77hUNBBBnq1", 1930 | "outputId": "8dd7cf18-db87-4363-81a6-da74d78b3e91" 1931 | }, 1932 | "outputs": [ 1933 | { 1934 | "data": { 1935 | "text/plain": [ 1936 | "'I love the Java language. I also use Java to build applications at work!'" 1937 | ] 1938 | }, 1939 | "execution_count": 61, 1940 | "metadata": { 1941 | "tags": [] 1942 | }, 1943 | "output_type": "execute_result" 1944 | } 1945 | ], 1946 | "source": [ 1947 | "# illustrating pattern substitution using sub and subn methods\n", 1948 | "re.sub(pattern, 'Java', s2, flags=re.IGNORECASE)" 1949 | ] 1950 | }, 1951 | { 1952 | "cell_type": "code", 1953 | "execution_count": 62, 1954 | "metadata": { 1955 | "colab": { 1956 | "base_uri": "https://localhost:8080/", 1957 | "height": 34 1958 | }, 1959 | "colab_type": "code", 1960 | "id": "1bKd3KxxBnq3", 1961 | "outputId": "104920a8-a5f2-4b66-d6a5-9284a5970092" 1962 | }, 1963 | "outputs": [ 1964 | { 1965 | "data": { 1966 | "text/plain": [ 1967 | "('I love the Java language. I also use Java to build applications at work!', 2)" 1968 | ] 1969 | }, 1970 | "execution_count": 62, 1971 | "metadata": { 1972 | "tags": [] 1973 | }, 1974 | "output_type": "execute_result" 1975 | } 1976 | ], 1977 | "source": [ 1978 | "re.subn(pattern, 'Java', s2, flags=re.IGNORECASE)" 1979 | ] 1980 | }, 1981 | { 1982 | "cell_type": "code", 1983 | "execution_count": 63, 1984 | "metadata": { 1985 | "colab": { 1986 | "base_uri": "https://localhost:8080/", 1987 | "height": 34 1988 | }, 1989 | "colab_type": "code", 1990 | "id": "nTYjDxldBnq5", 1991 | "outputId": "558a07ad-6da5-4e7e-f169-a70f338eacc4" 1992 | }, 1993 | "outputs": [ 1994 | { 1995 | "data": { 1996 | "text/plain": [ 1997 | "'Hèllo! this is Python 🐍'" 1998 | ] 1999 | }, 2000 | "execution_count": 63, 2001 | "metadata": { 2002 | "tags": [] 2003 | }, 2004 | "output_type": "execute_result" 2005 | } 2006 | ], 2007 | "source": [ 2008 | "# dealing with unicode matching using regexes\n", 2009 | "s = u'H\\u00e8llo! this is Python 🐍'\n", 2010 | "s" 2011 | ] 2012 | }, 2013 | { 2014 | "cell_type": "code", 2015 | "execution_count": 64, 2016 | "metadata": { 2017 | "colab": { 2018 | "base_uri": "https://localhost:8080/", 2019 | "height": 34 2020 | }, 2021 | "colab_type": "code", 2022 | "id": "ZIq5BxU9Bnq6", 2023 | "outputId": "2b18f8bb-d35f-4ecb-8d53-6bdc2bf08b70" 2024 | }, 2025 | "outputs": [ 2026 | { 2027 | "data": { 2028 | "text/plain": [ 2029 | "['Hèllo', 'this', 'is', 'Python']" 2030 | ] 2031 | }, 2032 | "execution_count": 64, 2033 | "metadata": { 2034 | "tags": [] 2035 | }, 2036 | "output_type": "execute_result" 2037 | } 2038 | ], 2039 | "source": [ 2040 | "re.findall(r'\\w+', s)" 2041 | ] 2042 | }, 2043 | { 2044 | "cell_type": "code", 2045 | "execution_count": 65, 2046 | "metadata": { 2047 | "colab": { 2048 | "base_uri": "https://localhost:8080/", 2049 | "height": 34 2050 | }, 2051 | "colab_type": "code", 2052 | "id": "88izNS1zBnq8", 2053 | "outputId": "6da32993-0634-418b-e5f6-7a38aa41da5a" 2054 | }, 2055 | "outputs": [ 2056 | { 2057 | "data": { 2058 | "text/plain": [ 2059 | "['Hèllo', 'Python']" 2060 | ] 2061 | }, 2062 | "execution_count": 65, 2063 | "metadata": { 2064 | "tags": [] 2065 | }, 2066 | "output_type": "execute_result" 2067 | } 2068 | ], 2069 | "source": [ 2070 | "re.findall(r\"[A-Z]\\w+\", s)" 2071 | ] 2072 | }, 2073 | { 2074 | "cell_type": "code", 2075 | "execution_count": 66, 2076 | "metadata": { 2077 | "colab": { 2078 | "base_uri": "https://localhost:8080/", 2079 | "height": 34 2080 | }, 2081 | "colab_type": "code", 2082 | "id": "BeKk3A7qBnq-", 2083 | "outputId": "6591c059-89ec-4552-aa5a-d98615c391c0" 2084 | }, 2085 | "outputs": [ 2086 | { 2087 | "data": { 2088 | "text/plain": [ 2089 | "['🐍']" 2090 | ] 2091 | }, 2092 | "execution_count": 66, 2093 | "metadata": { 2094 | "tags": [] 2095 | }, 2096 | "output_type": "execute_result" 2097 | } 2098 | ], 2099 | "source": [ 2100 | "emoji_pattern = r\"['\\U0001F300-\\U0001F5FF'|'\\U0001F600-\\U0001F64F'|'\\U0001F680-\\U0001F6FF'|'\\u2600-\\u26FF\\u2700-\\u27BF']\"\n", 2101 | "re.findall(emoji_pattern, s, re.UNICODE)" 2102 | ] 2103 | } 2104 | ], 2105 | "metadata": { 2106 | "accelerator": "GPU", 2107 | "anaconda-cloud": {}, 2108 | "colab": { 2109 | "collapsed_sections": [], 2110 | "name": "00-Introduction to NLP - Basics.ipynb", 2111 | "provenance": [] 2112 | }, 2113 | "kernelspec": { 2114 | "display_name": "Python 3", 2115 | "language": "python", 2116 | "name": "python3" 2117 | }, 2118 | "language_info": { 2119 | "codemirror_mode": { 2120 | "name": "ipython", 2121 | "version": 3 2122 | }, 2123 | "file_extension": ".py", 2124 | "mimetype": "text/x-python", 2125 | "name": "python", 2126 | "nbconvert_exporter": "python", 2127 | "pygments_lexer": "ipython3", 2128 | "version": "3.7.6" 2129 | } 2130 | }, 2131 | "nbformat": 4, 2132 | "nbformat_minor": 1 2133 | } 2134 | --------------------------------------------------------------------------------