From 44856be9b2cdec74f83957d14b607ef3103da03d Mon Sep 17 00:00:00 2001 From: GildaRIA <114354041+GildaRIA@users.noreply.github.com> Date: Sat, 18 Feb 2023 20:17:27 -0600 Subject: [PATCH 1/3] Delete challenge-1.ipynb --- your-code/challenge-1.ipynb | 246 ------------------------------------ 1 file changed, 246 deletions(-) delete mode 100644 your-code/challenge-1.ipynb diff --git a/your-code/challenge-1.ipynb b/your-code/challenge-1.ipynb deleted file mode 100644 index 4302084..0000000 --- a/your-code/challenge-1.ipynb +++ /dev/null @@ -1,246 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# String Operations Lab\n", - "\n", - "**Before your start:**\n", - "\n", - "- Read the README.md file\n", - "- Comment as much as you can and use the resources in the README.md file\n", - "- Happy learning!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import re" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Challenge 1 - Combining Strings\n", - "\n", - "Combining strings is an important skill to acquire. There are multiple ways of combining strings in Python, as well as combining strings with variables. We will explore this in the first challenge. In the cell below, combine the strings in the list and add spaces between the strings (do not add a space after the last string). Insert a period after the last string." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "str_list = ['Durante', 'un', 'tiempo', 'no', 'estuvo', 'segura', 'de', 'si', 'su', 'marido', 'era', 'su', 'marido']\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the cell below, use the list of strings to create a grocery list. Start the list with the string `Grocery list: ` and include a comma and a space between each item except for the last one. Include a period at the end. Only include foods in the list that start with the letter 'b' and ensure all foods are lower case." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "food_list = ['Bananas', 'Chocolate', 'bread', 'diapers', 'Ice Cream', 'Brownie Mix', 'broccoli']\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the cell below, write a function that computes the area of a circle using its radius. Compute the area of the circle and insert the radius and the area between the two strings. Make sure to include spaces between the variable and the strings. \n", - "\n", - "Note: You can use the techniques we have learned so far or use f-strings. F-strings allow us to embed code inside strings. You can read more about f-strings [here](https://www.python.org/dev/peps/pep-0498/)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import math\n", - "\n", - "string1 = \"The area of the circle with radius:\"\n", - "string2 = \"is:\"\n", - "radius = 4.5\n", - "\n", - "def area(x, pi = math.pi):\n", - " # This function takes a radius and returns the area of a circle. We also pass a default value for pi.\n", - " # Input: Float (and default value for pi)\n", - " # Output: Float\n", - " \n", - " # Sample input: 5.0\n", - " # Sample Output: 78.53981633\n", - " \n", - " # Your code here:\n", - " \n", - " \n", - "# Your output string here:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Challenge 2 - Splitting Strings\n", - "\n", - "We have first looked at combining strings into one long string. There are times where we need to do the opposite and split the string into smaller components for further analysis. \n", - "\n", - "In the cell below, split the string into a list of strings using the space delimiter. Count the frequency of each word in the string in a dictionary. Strip the periods, line breaks and commas from the text. Make sure to remove empty strings from your dictionary." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "poem = \"\"\"Some say the world will end in fire,\n", - "Some say in ice.\n", - "From what I’ve tasted of desire\n", - "I hold with those who favor fire.\n", - "But if it had to perish twice,\n", - "I think I know enough of hate\n", - "To say that for destruction ice\n", - "Is also great\n", - "And would suffice.\"\"\"\n", - "\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the cell below, find all the words that appear in the text and do not appear in the blacklist. You must parse the string but can choose any data structure you wish for the words that do not appear in the blacklist. Remove all non letter characters and convert all words to lower case." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "blacklist = ['and', 'as', 'an', 'a', 'the', 'in', 'it']\n", - "\n", - "poem = \"\"\"I was angry with my friend; \n", - "I told my wrath, my wrath did end.\n", - "I was angry with my foe: \n", - "I told it not, my wrath did grow. \n", - "\n", - "And I waterd it in fears,\n", - "Night & morning with my tears: \n", - "And I sunned it with smiles,\n", - "And with soft deceitful wiles. \n", - "\n", - "And it grew both day and night. \n", - "Till it bore an apple bright. \n", - "And my foe beheld it shine,\n", - "And he knew that it was mine. \n", - "\n", - "And into my garden stole, \n", - "When the night had veild the pole; \n", - "In the morning glad I see; \n", - "My foe outstretched beneath the tree.\"\"\"\n", - "\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Challenge 3 - Regular Expressions\n", - "\n", - "Sometimes, we would like to perform more complex manipulations of our string. This is where regular expressions come in handy. In the cell below, return all characters that are upper case from the string specified below." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "poem = \"\"\"The apparition of these faces in the crowd;\n", - "Petals on a wet, black bough.\"\"\"\n", - "\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the cell below, filter the list provided and return all elements of the list containing a number. To filter the list, use the `re.search` function. Check if the function does not return `None`. You can read more about the `re.search` function [here](https://docs.python.org/3/library/re.html)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "data = ['123abc', 'abc123', 'JohnSmith1', 'ABBY4', 'JANE']\n", - "\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Bonus Challenge - Regular Expressions II\n", - "\n", - "In the cell below, filter the list provided to keep only strings containing at least one digit and at least one lower case letter. As in the previous question, use the `re.search` function and check that the result is not `None`.\n", - "\n", - "To read more about regular expressions, check out [this link](https://developers.google.com/edu/python/regular-expressions)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "data = ['123abc', 'abc123', 'JohnSmith1', 'ABBY4', 'JANE']\n", - "# Your code here:\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.7.2" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} From f02cbd920db3e943d37856ba74fc72827a603511 Mon Sep 17 00:00:00 2001 From: GildaRIA <114354041+GildaRIA@users.noreply.github.com> Date: Sat, 18 Feb 2023 20:17:42 -0600 Subject: [PATCH 2/3] Delete challenge-2.ipynb --- your-code/challenge-2.ipynb | 341 ------------------------------------ 1 file changed, 341 deletions(-) delete mode 100644 your-code/challenge-2.ipynb diff --git a/your-code/challenge-2.ipynb b/your-code/challenge-2.ipynb deleted file mode 100644 index 87c5656..0000000 --- a/your-code/challenge-2.ipynb +++ /dev/null @@ -1,341 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Bag of Words Lab\n", - "\n", - "## Introduction\n", - "\n", - "**Bag of words (BoW)** is an important technique in text mining and [information retrieval](https://en.wikipedia.org/wiki/Information_retrieval). BoW uses term-frequency vectors to represent the content of text documents which makes it possible to use mathematics and computer programs to analyze and compare text documents.\n", - "\n", - "BoW contains the following information:\n", - "\n", - "1. A dictionary of all the terms (words) in the text documents. The terms are normalized in terms of the letter case (e.g. `Ironhack` => `ironhack`), tense (e.g. `had` => `have`), singular form (e.g. `students` => `student`), etc.\n", - "1. The number of occurrences of each normalized term in each document.\n", - "\n", - "For example, assume we have three text documents:\n", - "\n", - "DOC 1: **Ironhack is cool.**\n", - "\n", - "DOC 2: **I love Ironhack.**\n", - "\n", - "DOC 3: **I am a student at Ironhack.**\n", - "\n", - "The BoW of the above documents looks like below:\n", - "\n", - "| TERM | DOC 1 | DOC 2 | Doc 3 |\n", - "|---|---|---|---|\n", - "| a | 0 | 0 | 1 |\n", - "| am | 0 | 0 | 1 |\n", - "| at | 0 | 0 | 1 |\n", - "| cool | 1 | 0 | 0 |\n", - "| i | 0 | 1 | 1 |\n", - "| ironhack | 1 | 1 | 1 |\n", - "| is | 1 | 0 | 0 |\n", - "| love | 0 | 1 | 0 |\n", - "| student | 0 | 0 | 1 |\n", - "\n", - "\n", - "The term-frequency array of each document in BoW can be considered a high-dimensional vector. Data scientists use these vectors to represent the content of the documents. For instance, DOC 1 is represented with `[0, 0, 0, 1, 0, 1, 1, 0, 0]`, DOC 2 is represented with `[0, 0, 0, 0, 1, 1, 0, 1, 0]`, and DOC 3 is represented with `[1, 1, 1, 0, 1, 1, 0, 0, 1]`. **Two documents are considered identical if their vector representations have close [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity).**\n", - "\n", - "In real practice there are many additional techniques to improve the text mining accuracy such as using [stop words](https://en.wikipedia.org/wiki/Stop_words) (i.e. neglecting common words such as `a`, `I`, `to` that don't contribute much meaning), synonym list (e.g. consider `New York City` the same as `NYC` and `Big Apple`), and HTML tag removal if the data sources are webpages. In Module 3 you will learn how to use those advanced techniques for [natural language processing](https://en.wikipedia.org/wiki/Natural_language_processing), a component of text mining.\n", - "\n", - "In real text mining projects data analysts use packages such as Scikit-Learn and NLTK, which you will learn in Module 3, to extract BoW from texts. In this exercise, however, we would like you to create BoW manually with Python. This is because by manually creating BoW you can better understand the concept and also practice the Python skills you have learned so far." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The Challenge\n", - "\n", - "We need to create a BoW from a list of documents. The documents (`doc1.txt`, `doc2.txt`, and `doc3.txt`) can be found in the `your-code` directory of this exercise. You will read the content of each document into an array of strings named `corpus`.\n", - "\n", - "*What is a corpus (plural: corpora)? Read the reference in the README file.*\n", - "\n", - "Your challenge is to use Python to generate the BoW of these documents. Your BoW should look like below:\n", - "\n", - "```python\n", - "bag_of_words = ['a', 'am', 'at', 'cool', 'i', 'ironhack', 'is', 'love', 'student']\n", - "\n", - "term_freq = [\n", - " [0, 0, 0, 1, 0, 1, 1, 0, 0],\n", - " [0, 0, 0, 0, 1, 1, 0, 1, 0],\n", - " [1, 1, 1, 0, 1, 1, 0, 0, 1],\n", - "]\n", - "```\n", - "\n", - "Now let's define the `docs` array that contains the paths of `doc1.txt`, `doc2.txt`, and `doc3.txt`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "docs = ['doc1.txt', 'doc2.txt', 'doc3.txt']" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Define an empty array `corpus` that will contain the content strings of the docs. Loop `docs` and read the content of each doc into the `corpus` array." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "corpus = []\n", - "\n", - "# Write your code here\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Print `corpus`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(corpus)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You expected to see:\n", - "\n", - "```['ironhack is cool', 'i love ironhack', 'i am a student at ironhack']```\n", - "\n", - "But you actually saw:\n", - "\n", - "```['Ironhack is cool.', 'I love Ironhack.', 'I am a student at Ironhack.']```\n", - "\n", - "This is because you haven't done two important steps:\n", - "\n", - "1. Remove punctuation from the strings\n", - "\n", - "1. Convert strings to lowercase\n", - "\n", - "Write your code below to process `corpus` (convert to lower case and remove special characters)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Write your code here" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now define `bag_of_words` as an empty array. It will be used to store the unique terms in `corpus`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "bag_of_words = []" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Loop through `corpus`. In each loop, do the following:\n", - "\n", - "1. Break the string into an array of terms. \n", - "1. Create a sub-loop to iterate the terms array. \n", - " * In each sub-loop, you'll check if the current term is already contained in `bag_of_words`. If not in `bag_of_words`, append it to the array." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Write your code here" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Print `bag_of_words`. You should see: \n", - "\n", - "```['ironhack', 'is', 'cool', 'i', 'love', 'am', 'a', 'student', 'at']```\n", - "\n", - "If not, fix your code in the previous cell." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(bag_of_words)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now we define an empty array called `term_freq`. Loop `corpus` for a second time. In each loop, create a sub-loop to iterate the terms in `bag_of_words`. Count how many times each term appears in each doc of `corpus`. Append the term-frequency array to `term_freq`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "term_freq = []\n", - "\n", - "# Write your code here" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Print `term_freq`. You should see:\n", - "\n", - "```[[1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 0, 1, 1, 1, 1]]```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(term_freq)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**If your output is correct, congratulations! You've solved the challenge!**\n", - "\n", - "If not, go back and check for errors in your code." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Bonus Question\n", - "\n", - "Optimize your solution for the above question by removing stop words from the BoW. For your convenience, a list of stop words is defined for you in the next cell. With the stop words removed, your output should look like:\n", - "\n", - "```\n", - "bag_of_words = [am', 'at', 'cool', ironhack', 'is', 'love', 'student']\n", - "\n", - "term_freq = [\n", - "\t[0, 0, 1, 1, 1, 0, 0],\n", - " \t[0, 0, 0, 1, 0, 1, 0],\n", - " \t[1, 1, 0, 1, 0, 0, 1]\n", - "]\n", - "```\n", - "\n", - "**Requirements:**\n", - "\n", - "1. Combine all your previous codes to the cell below.\n", - "1. Improve your solution by ignoring stop words in `bag_of_words`.\n", - "\n", - "After you're done, your `bag_of_words` should be:\n", - "\n", - "```['ironhack', 'is', 'cool', 'love', 'am', 'student', 'at']```\n", - "\n", - "And your `term_freq` should be:\n", - "\n", - "```[[1, 1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1, 1]]```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "stop_words = ['all', 'six', 'less', 'being', 'indeed', 'over', 'move', 'anyway', 'fifty', 'four', 'not', 'own', 'through', 'yourselves', 'go', 'where', 'mill', 'only', 'find', 'before', 'one', 'whose', 'system', 'how', 'somewhere', 'with', 'thick', 'show', 'had', 'enough', 'should', 'to', 'must', 'whom', 'seeming', 'under', 'ours', 'has', 'might', 'thereafter', 'latterly', 'do', 'them', 'his', 'around', 'than', 'get', 'very', 'de', 'none', 'cannot', 'every', 'whether', 'they', 'front', 'during', 'thus', 'now', 'him', 'nor', 'name', 'several', 'hereafter', 'always', 'who', 'cry', 'whither', 'this', 'someone', 'either', 'each', 'become', 'thereupon', 'sometime', 'side', 'two', 'therein', 'twelve', 'because', 'often', 'ten', 'our', 'eg', 'some', 'back', 'up', 'namely', 'towards', 'are', 'further', 'beyond', 'ourselves', 'yet', 'out', 'even', 'will', 'what', 'still', 'for', 'bottom', 'mine', 'since', 'please', 'forty', 'per', 'its', 'everything', 'behind', 'un', 'above', 'between', 'it', 'neither', 'seemed', 'ever', 'across', 'she', 'somehow', 'be', 'we', 'full', 'never', 'sixty', 'however', 'here', 'otherwise', 'were', 'whereupon', 'nowhere', 'although', 'found', 'alone', 're', 'along', 'fifteen', 'by', 'both', 'about', 'last', 'would', 'anything', 'via', 'many', 'could', 'thence', 'put', 'against', 'keep', 'etc', 'amount', 'became', 'ltd', 'hence', 'onto', 'or', 'con', 'among', 'already', 'co', 'afterwards', 'formerly', 'within', 'seems', 'into', 'others', 'while', 'whatever', 'except', 'down', 'hers', 'everyone', 'done', 'least', 'another', 'whoever', 'moreover', 'couldnt', 'throughout', 'anyhow', 'yourself', 'three', 'from', 'her', 'few', 'together', 'top', 'there', 'due', 'been', 'next', 'anyone', 'eleven', 'much', 'call', 'therefore', 'interest', 'then', 'thru', 'themselves', 'hundred', 'was', 'sincere', 'empty', 'more', 'himself', 'elsewhere', 'mostly', 'on', 'fire', 'am', 'becoming', 'hereby', 'amongst', 'else', 'part', 'everywhere', 'too', 'herself', 'former', 'those', 'he', 'me', 'myself', 'made', 'twenty', 'these', 'bill', 'cant', 'us', 'until', 'besides', 'nevertheless', 'below', 'anywhere', 'nine', 'can', 'of', 'your', 'toward', 'my', 'something', 'and', 'whereafter', 'whenever', 'give', 'almost', 'wherever', 'is', 'describe', 'beforehand', 'herein', 'an', 'as', 'itself', 'at', 'have', 'in', 'seem', 'whence', 'ie', 'any', 'fill', 'again', 'hasnt', 'inc', 'thereby', 'thin', 'no', 'perhaps', 'latter', 'meanwhile', 'when', 'detail', 'same', 'wherein', 'beside', 'also', 'that', 'other', 'take', 'which', 'becomes', 'you', 'if', 'nobody', 'see', 'though', 'may', 'after', 'upon', 'most', 'hereupon', 'eight', 'but', 'serious', 'nothing', 'such', 'why', 'a', 'off', 'whereby', 'third', 'i', 'whole', 'noone', 'sometimes', 'well', 'amoungst', 'yours', 'their', 'rather', 'without', 'so', 'five', 'the', 'first', 'whereas', 'once']\n", - "\n", - "# Write your code below\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Additional Challenge for the Nerds\n", - "\n", - "We will learn Scikit-Learn in Module 3 which has built in the BoW feature. Try to use Scikit-Learn to generate the BoW for this challenge and check whether the output is the same as yours. You will need to do some googling to find out how to use Scikit-Learn to generate BoW.\n", - "\n", - "**Notes:**\n", - "\n", - "* To install Scikit-Learn, use `pip install sklearn`. \n", - "\n", - "* Scikit-Learn removes stop words by default. You don't need to manually remove stop words.\n", - "\n", - "* Scikit-Learn's output has slightly different format from the output example demonstrated above. It's ok, you don't need to convert the Scikit-Learn output.\n", - "\n", - "The Scikit-Learn output will look like below:\n", - "\n", - "```python\n", - "# BoW:\n", - "{u'love': 5, u'ironhack': 3, u'student': 6, u'is': 4, u'cool': 2, u'am': 0, u'at': 1}\n", - "\n", - "# term_freq:\n", - "[[0 0 1 1 1 0 0]\n", - " [0 0 0 1 0 1 0]\n", - " [1 1 0 1 0 0 1]]\n", - " ```" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.7.2" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} From c8ba901fd49b1ce1e3138bca9dffeeedc3e4a76c Mon Sep 17 00:00:00 2001 From: GildaRIA <114354041+GildaRIA@users.noreply.github.com> Date: Sat, 18 Feb 2023 20:18:34 -0600 Subject: [PATCH 3/3] Add files via upload --- your-code/challenge-1.ipynb | 354 +++++++++++++++++++++++++++++ your-code/challenge-2.ipynb | 430 ++++++++++++++++++++++++++++++++++++ 2 files changed, 784 insertions(+) create mode 100644 your-code/challenge-1.ipynb create mode 100644 your-code/challenge-2.ipynb diff --git a/your-code/challenge-1.ipynb b/your-code/challenge-1.ipynb new file mode 100644 index 0000000..87818c4 --- /dev/null +++ b/your-code/challenge-1.ipynb @@ -0,0 +1,354 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# String Operations Lab\n", + "\n", + "**Before your start:**\n", + "\n", + "- Read the README.md file\n", + "- Comment as much as you can and use the resources in the README.md file\n", + "- Happy learning!" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import re" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Challenge 1 - Combining Strings\n", + "\n", + "Combining strings is an important skill to acquire. There are multiple ways of combining strings in Python, as well as combining strings with variables. We will explore this in the first challenge. In the cell below, combine the strings in the list and add spaces between the strings (do not add a space after the last string). Insert a period after the last string." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Durante un tiempo no estuvo segura de si su marido era su marido.\n" + ] + } + ], + "source": [ + "str_list = ['Durante', 'un', 'tiempo', 'no', 'estuvo', 'segura', 'de', 'si', 'su', 'marido', 'era', 'su', 'marido']\n", + "# Your code here:\n", + "sep = ' '\n", + "nueva_string = sep.join(str_list) + '.'\n", + "print(nueva_string)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the cell below, use the list of strings to create a grocery list. Start the list with the string `Grocery list: ` and include a comma and a space between each item except for the last one. Include a period at the end. Only include foods in the list that start with the letter 'b' and ensure all foods are lower case." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Grocery list: bananas, bread, brownie mix, broccoli.\n" + ] + } + ], + "source": [ + "food_list = ['Bananas', 'Chocolate', 'bread', 'diapers', 'Ice Cream', 'Brownie Mix', 'broccoli']\n", + "food_list = [food.lower() for food in food_list if food.lower().startswith('b')]\n", + "grocery_list = ', '.join(food_list)\n", + "grocery_list = \"Grocery list: \" + grocery_list + \".\"\n", + "print(grocery_list)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the cell below, write a function that computes the area of a circle using its radius. Compute the area of the circle and insert the radius and the area between the two strings. Make sure to include spaces between the variable and the strings. \n", + "\n", + "Note: You can use the techniques we have learned so far or use f-strings. F-strings allow us to embed code inside strings. You can read more about f-strings [here](https://www.python.org/dev/peps/pep-0498/)." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The area of the circle with radius: 4.5 is: 63.61725123519331\n" + ] + } + ], + "source": [ + "import math\n", + "\n", + "def area(radius, pi = math.pi):\n", + " return pi * (radius**2)\n", + "\n", + "string1 = \"The area of the circle with radius:\"\n", + "string2 = \"is:\"\n", + "radius = 4.5\n", + "\n", + "area_of_circle = area(radius)\n", + "\n", + "print(string1 + \" \" + str(radius) + \" \" + string2 + \" \" + str(area_of_circle))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Challenge 2 - Splitting Strings\n", + "\n", + "We have first looked at combining strings into one long string. There are times where we need to do the opposite and split the string into smaller components for further analysis. \n", + "\n", + "In the cell below, split the string into a list of strings using the space delimiter. Count the frequency of each word in the string in a dictionary. Strip the periods, line breaks and commas from the text. Make sure to remove empty strings from your dictionary." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'Some': 2, 'say': 3, 'the': 1, 'world': 1, 'will': 1, 'end': 1, 'in': 2, 'fire': 2, 'ice': 2, 'From': 1, 'what': 1, 'I': 4, 've': 1, 'tasted': 1, 'of': 2, 'desire': 1, 'hold': 1, 'with': 1, 'those': 1, 'who': 1, 'favor': 1, 'But': 1, 'if': 1, 'it': 1, 'had': 1, 'to': 1, 'perish': 1, 'twice': 1, 'think': 1, 'know': 1, 'enough': 1, 'hate': 1, 'To': 1, 'that': 1, 'for': 1, 'destruction': 1, 'Is': 1, 'also': 1, 'great': 1, 'And': 1, 'would': 1, 'suffice': 1}\n" + ] + } + ], + "source": [ + "poem = \"\"\"Some say the world will end in fire,\n", + "Some say in ice.\n", + "From what I’ve tasted of desire\n", + "I hold with those who favor fire.\n", + "But if it had to perish twice,\n", + "I think I know enough of hate\n", + "To say that for destruction ice\n", + "Is also great\n", + "And would suffice.\"\"\"\n", + "\n", + "words = re.findall(r'\\b\\w+\\b', poem)\n", + "\n", + "words = [word.strip(\".,\\n\") for word in words]\n", + "\n", + "words = list(filter(lambda x: x != \"\", words))\n", + "\n", + "word_freq = {}\n", + "for word in words:\n", + " if word in word_freq:\n", + " word_freq[word] += 1\n", + " else:\n", + " word_freq[word] = 1\n", + "\n", + "print(word_freq)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the cell below, find all the words that appear in the text and do not appear in the blacklist. You must parse the string but can choose any data structure you wish for the words that do not appear in the blacklist. Remove all non letter characters and convert all words to lower case." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['i', 'was', 'angry', 'with', 'my', 'friend', 'i', 'told', 'my', 'wrath', 'my', 'wrath', 'did', 'end', 'i', 'was', 'angry', 'with', 'my', 'foe', 'i', 'told', 'not', 'my', 'wrath', 'did', 'grow', 'i', 'waterd', 'fears', 'night', 'morning', 'with', 'my', 'tears', 'i', 'sunned', 'with', 'smiles', 'with', 'soft', 'deceitful', 'wiles', 'grew', 'both', 'day', 'night', 'till', 'bore', 'apple', 'bright', 'my', 'foe', 'beheld', 'shine', 'he', 'knew', 'that', 'was', 'mine', 'into', 'my', 'garden', 'stole', 'when', 'night', 'had', 'veild', 'pole', 'morning', 'glad', 'i', 'see', 'my', 'foe', 'outstretched', 'beneath', 'tree']\n" + ] + } + ], + "source": [ + "blacklist = ['and', 'as', 'an', 'a', 'the', 'in', 'it']\n", + "\n", + "poem = \"\"\"I was angry with my friend; \n", + "I told my wrath, my wrath did end.\n", + "I was angry with my foe: \n", + "I told it not, my wrath did grow. \n", + "\n", + "And I waterd it in fears,\n", + "Night & morning with my tears: \n", + "And I sunned it with smiles,\n", + "And with soft deceitful wiles. \n", + "\n", + "And it grew both day and night. \n", + "Till it bore an apple bright. \n", + "And my foe beheld it shine,\n", + "And he knew that it was mine. \n", + "\n", + "And into my garden stole, \n", + "When the night had veild the pole; \n", + "In the morning glad I see; \n", + "My foe outstretched beneath the tree.\"\"\"\n", + "\n", + "poem = re.sub(r\"[^a-zA-Z]\", \" \", poem)\n", + "poem = poem.lower()\n", + "\n", + "words = poem.split()\n", + "\n", + "words = [word for word in words if word not in blacklist]\n", + "\n", + "print(words)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Challenge 3 - Regular Expressions\n", + "\n", + "Sometimes, we would like to perform more complex manipulations of our string. This is where regular expressions come in handy. In the cell below, return all characters that are upper case from the string specified below." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['T', 'P']\n" + ] + } + ], + "source": [ + "poem = \"\"\"The apparition of these faces in the crowd;\n", + "Petals on a wet, black bough.\"\"\"\n", + "\n", + "uppercase_regex = r\"[A-Z]\"\n", + "uppercase_chars = re.findall(uppercase_regex, poem)\n", + "\n", + "print(uppercase_chars)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the cell below, filter the list provided and return all elements of the list containing a number. To filter the list, use the `re.search` function. Check if the function does not return `None`. You can read more about the `re.search` function [here](https://docs.python.org/3/library/re.html)." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['123abc', 'abc123', 'JohnSmith1', 'ABBY4']\n" + ] + } + ], + "source": [ + "data = ['123abc', 'abc123', 'JohnSmith1', 'ABBY4', 'JANE']\n", + "\n", + "number_regex = r'\\d'\n", + "number_items = [item for item in data if re.search(number_regex, item)]\n", + "\n", + "print(number_items)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Bonus Challenge - Regular Expressions II\n", + "\n", + "In the cell below, filter the list provided to keep only strings containing at least one digit and at least one lower case letter. As in the previous question, use the `re.search` function and check that the result is not `None`.\n", + "\n", + "To read more about regular expressions, check out [this link](https://developers.google.com/edu/python/regular-expressions)." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['123abc', 'abc123', 'JohnSmith1']\n" + ] + } + ], + "source": [ + "data = ['123abc', 'abc123', 'JohnSmith1', 'ABBY4', 'JANE']\n", + "\n", + "regex = r'^(?=.*\\d)(?=.*[a-z]).*$'\n", + "filtered_data = [item for item in data if re.search(regex, item)]\n", + "\n", + "print(filtered_data)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.12" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/your-code/challenge-2.ipynb b/your-code/challenge-2.ipynb new file mode 100644 index 0000000..dd27f81 --- /dev/null +++ b/your-code/challenge-2.ipynb @@ -0,0 +1,430 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Bag of Words Lab\n", + "\n", + "## Introduction\n", + "\n", + "**Bag of words (BoW)** is an important technique in text mining and [information retrieval](https://en.wikipedia.org/wiki/Information_retrieval). BoW uses term-frequency vectors to represent the content of text documents which makes it possible to use mathematics and computer programs to analyze and compare text documents.\n", + "\n", + "BoW contains the following information:\n", + "\n", + "1. A dictionary of all the terms (words) in the text documents. The terms are normalized in terms of the letter case (e.g. `Ironhack` => `ironhack`), tense (e.g. `had` => `have`), singular form (e.g. `students` => `student`), etc.\n", + "1. The number of occurrences of each normalized term in each document.\n", + "\n", + "For example, assume we have three text documents:\n", + "\n", + "DOC 1: **Ironhack is cool.**\n", + "\n", + "DOC 2: **I love Ironhack.**\n", + "\n", + "DOC 3: **I am a student at Ironhack.**\n", + "\n", + "The BoW of the above documents looks like below:\n", + "\n", + "| TERM | DOC 1 | DOC 2 | Doc 3 |\n", + "|---|---|---|---|\n", + "| a | 0 | 0 | 1 |\n", + "| am | 0 | 0 | 1 |\n", + "| at | 0 | 0 | 1 |\n", + "| cool | 1 | 0 | 0 |\n", + "| i | 0 | 1 | 1 |\n", + "| ironhack | 1 | 1 | 1 |\n", + "| is | 1 | 0 | 0 |\n", + "| love | 0 | 1 | 0 |\n", + "| student | 0 | 0 | 1 |\n", + "\n", + "\n", + "The term-frequency array of each document in BoW can be considered a high-dimensional vector. Data scientists use these vectors to represent the content of the documents. For instance, DOC 1 is represented with `[0, 0, 0, 1, 0, 1, 1, 0, 0]`, DOC 2 is represented with `[0, 0, 0, 0, 1, 1, 0, 1, 0]`, and DOC 3 is represented with `[1, 1, 1, 0, 1, 1, 0, 0, 1]`. **Two documents are considered identical if their vector representations have close [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity).**\n", + "\n", + "In real practice there are many additional techniques to improve the text mining accuracy such as using [stop words](https://en.wikipedia.org/wiki/Stop_words) (i.e. neglecting common words such as `a`, `I`, `to` that don't contribute much meaning), synonym list (e.g. consider `New York City` the same as `NYC` and `Big Apple`), and HTML tag removal if the data sources are webpages. In Module 3 you will learn how to use those advanced techniques for [natural language processing](https://en.wikipedia.org/wiki/Natural_language_processing), a component of text mining.\n", + "\n", + "In real text mining projects data analysts use packages such as Scikit-Learn and NLTK, which you will learn in Module 3, to extract BoW from texts. In this exercise, however, we would like you to create BoW manually with Python. This is because by manually creating BoW you can better understand the concept and also practice the Python skills you have learned so far." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import os" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "tags": [] + }, + "source": [ + "## The Challenge\n", + "\n", + "We need to create a BoW from a list of documents. The documents (`doc1.txt`, `doc2.txt`, and `doc3.txt`) can be found in the `your-code` directory of this exercise. You will read the content of each document into an array of strings named `corpus`.\n", + "\n", + "*What is a corpus (plural: corpora)? Read the reference in the README file.*\n", + "\n", + "Your challenge is to use Python to generate the BoW of these documents. Your BoW should look like below:\n", + "\n", + "```python\n", + "bag_of_words = ['a', 'am', 'at', 'cool', 'i', 'ironhack', 'is', 'love', 'student']\n", + "\n", + "term_freq = [\n", + " [0, 0, 0, 1, 0, 1, 1, 0, 0],\n", + " [0, 0, 0, 0, 1, 1, 0, 1, 0],\n", + " [1, 1, 1, 0, 1, 1, 0, 0, 1],\n", + "]\n", + "```\n", + "\n", + "Now let's define the `docs` array that contains the paths of `doc1.txt`, `doc2.txt`, and `doc3.txt`." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "docs = ['doc1.txt', 'doc2.txt', 'doc3.txt']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Define an empty array `corpus` that will contain the content strings of the docs. Loop `docs` and read the content of each doc into the `corpus` array." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "ename": "TypeError", + "evalue": "listdir: path should be string, bytes, os.PathLike or None, not list", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "Input \u001b[1;32mIn [8]\u001b[0m, in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m corpus \u001b[38;5;241m=\u001b[39m []\n\u001b[1;32m----> 3\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m filename \u001b[38;5;129;01min\u001b[39;00m \u001b[43mos\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mlistdir\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocs\u001b[49m\u001b[43m)\u001b[49m:\n\u001b[0;32m 4\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m filename\u001b[38;5;241m.\u001b[39mendswith(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m.txt\u001b[39m\u001b[38;5;124m\"\u001b[39m):\n\u001b[0;32m 5\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28mopen\u001b[39m(os\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39mjoin(docs, filename), \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mr\u001b[39m\u001b[38;5;124m\"\u001b[39m) \u001b[38;5;28;01mas\u001b[39;00m f:\n", + "\u001b[1;31mTypeError\u001b[0m: listdir: path should be string, bytes, os.PathLike or None, not list" + ] + } + ], + "source": [ + "corpus = []\n", + "\n", + "for filename in os.listdir(docs):\n", + " if filename.endswith(\".txt\"):\n", + " with open(os.path.join(docs, filename), \"r\") as f:\n", + " text = f.read()\n", + " corpus.extend(text.split())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print `corpus`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print(corpus)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You expected to see:\n", + "\n", + "```['ironhack is cool', 'i love ironhack', 'i am a student at ironhack']```\n", + "\n", + "But you actually saw:\n", + "\n", + "```['Ironhack is cool.', 'I love Ironhack.', 'I am a student at Ironhack.']```\n", + "\n", + "This is because you haven't done two important steps:\n", + "\n", + "1. Remove punctuation from the strings\n", + "\n", + "1. Convert strings to lowercase\n", + "\n", + "Write your code below to process `corpus` (convert to lower case and remove special characters)." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'docs_dir' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "Input \u001b[1;32mIn [10]\u001b[0m, in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m corpus \u001b[38;5;241m=\u001b[39m []\n\u001b[1;32m----> 2\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m filename \u001b[38;5;129;01min\u001b[39;00m os\u001b[38;5;241m.\u001b[39mlistdir(\u001b[43mdocs_dir\u001b[49m):\n\u001b[0;32m 3\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m filename\u001b[38;5;241m.\u001b[39mendswith(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m.txt\u001b[39m\u001b[38;5;124m\"\u001b[39m):\n\u001b[0;32m 4\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28mopen\u001b[39m(os\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39mjoin(docs_dir, filename), \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mr\u001b[39m\u001b[38;5;124m\"\u001b[39m) \u001b[38;5;28;01mas\u001b[39;00m f:\n", + "\u001b[1;31mNameError\u001b[0m: name 'docs_dir' is not defined" + ] + } + ], + "source": [ + "corpus = []\n", + "for filename in os.listdir(docs_dir):\n", + " if filename.endswith(\".txt\"):\n", + " with open(os.path.join(docs_dir, filename), \"r\") as f:\n", + " text = f.read()\n", + " text = text.translate(str.maketrans(\"\", \"\", string.punctuation)).lower()\n", + " corpus.extend(text.split())\n", + "\n", + "print(corpus)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now define `bag_of_words` as an empty array. It will be used to store the unique terms in `corpus`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "bag_of_words = []" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Loop through `corpus`. In each loop, do the following:\n", + "\n", + "1. Break the string into an array of terms. \n", + "1. Create a sub-loop to iterate the terms array. \n", + " * In each sub-loop, you'll check if the current term is already contained in `bag_of_words`. If not in `bag_of_words`, append it to the array." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'bag_of_words' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "Input \u001b[1;32mIn [11]\u001b[0m, in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m term \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m bag_of_words:\n\u001b[0;32m 5\u001b[0m bag_of_words\u001b[38;5;241m.\u001b[39mappend(term)\n\u001b[1;32m----> 6\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mbag_of_words\u001b[49m)\n", + "\u001b[1;31mNameError\u001b[0m: name 'bag_of_words' is not defined" + ] + } + ], + "source": [ + "for doc in corpus:\n", + " terms = doc.split()\n", + " for term in terms:\n", + " if term not in bag_of_words:\n", + " bag_of_words.append(term)\n", + "print(bag_of_words)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print `bag_of_words`. You should see: \n", + "\n", + "```['ironhack', 'is', 'cool', 'i', 'love', 'am', 'a', 'student', 'at']```\n", + "\n", + "If not, fix your code in the previous cell." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'bag_of_words' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "Input \u001b[1;32mIn [12]\u001b[0m, in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mbag_of_words\u001b[49m)\n", + "\u001b[1;31mNameError\u001b[0m: name 'bag_of_words' is not defined" + ] + } + ], + "source": [ + "print(bag_of_words)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we define an empty array called `term_freq`. Loop `corpus` for a second time. In each loop, create a sub-loop to iterate the terms in `bag_of_words`. Count how many times each term appears in each doc of `corpus`. Append the term-frequency array to `term_freq`." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "term_freq = []\n", + "\n", + "for doc in corpus:\n", + " doc_term_freq = []\n", + " for term in bag_of_words:\n", + " count = doc.lower().translate(str.maketrans('', '', string.punctuation)).split().count(term)\n", + " doc_term_freq.append(count)\n", + " term_freq.append(doc_term_freq)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print `term_freq`. You should see:\n", + "\n", + "```[[1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 0, 1, 1, 1, 1]]```" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[]\n" + ] + } + ], + "source": [ + "print(term_freq)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**If your output is correct, congratulations! You've solved the challenge!**\n", + "\n", + "If not, go back and check for errors in your code." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Bonus Question\n", + "\n", + "Optimize your solution for the above question by removing stop words from the BoW. For your convenience, a list of stop words is defined for you in the next cell. With the stop words removed, your output should look like:\n", + "\n", + "```\n", + "bag_of_words = [am', 'at', 'cool', ironhack', 'is', 'love', 'student']\n", + "\n", + "term_freq = [\n", + "\t[0, 0, 1, 1, 1, 0, 0],\n", + " \t[0, 0, 0, 1, 0, 1, 0],\n", + " \t[1, 1, 0, 1, 0, 0, 1]\n", + "]\n", + "```\n", + "\n", + "**Requirements:**\n", + "\n", + "1. Combine all your previous codes to the cell below.\n", + "1. Improve your solution by ignoring stop words in `bag_of_words`.\n", + "\n", + "After you're done, your `bag_of_words` should be:\n", + "\n", + "```['ironhack', 'is', 'cool', 'love', 'am', 'student', 'at']```\n", + "\n", + "And your `term_freq` should be:\n", + "\n", + "```[[1, 1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1, 1]]```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "stop_words = ['all', 'six', 'less', 'being', 'indeed', 'over', 'move', 'anyway', 'fifty', 'four', 'not', 'own', 'through', 'yourselves', 'go', 'where', 'mill', 'only', 'find', 'before', 'one', 'whose', 'system', 'how', 'somewhere', 'with', 'thick', 'show', 'had', 'enough', 'should', 'to', 'must', 'whom', 'seeming', 'under', 'ours', 'has', 'might', 'thereafter', 'latterly', 'do', 'them', 'his', 'around', 'than', 'get', 'very', 'de', 'none', 'cannot', 'every', 'whether', 'they', 'front', 'during', 'thus', 'now', 'him', 'nor', 'name', 'several', 'hereafter', 'always', 'who', 'cry', 'whither', 'this', 'someone', 'either', 'each', 'become', 'thereupon', 'sometime', 'side', 'two', 'therein', 'twelve', 'because', 'often', 'ten', 'our', 'eg', 'some', 'back', 'up', 'namely', 'towards', 'are', 'further', 'beyond', 'ourselves', 'yet', 'out', 'even', 'will', 'what', 'still', 'for', 'bottom', 'mine', 'since', 'please', 'forty', 'per', 'its', 'everything', 'behind', 'un', 'above', 'between', 'it', 'neither', 'seemed', 'ever', 'across', 'she', 'somehow', 'be', 'we', 'full', 'never', 'sixty', 'however', 'here', 'otherwise', 'were', 'whereupon', 'nowhere', 'although', 'found', 'alone', 're', 'along', 'fifteen', 'by', 'both', 'about', 'last', 'would', 'anything', 'via', 'many', 'could', 'thence', 'put', 'against', 'keep', 'etc', 'amount', 'became', 'ltd', 'hence', 'onto', 'or', 'con', 'among', 'already', 'co', 'afterwards', 'formerly', 'within', 'seems', 'into', 'others', 'while', 'whatever', 'except', 'down', 'hers', 'everyone', 'done', 'least', 'another', 'whoever', 'moreover', 'couldnt', 'throughout', 'anyhow', 'yourself', 'three', 'from', 'her', 'few', 'together', 'top', 'there', 'due', 'been', 'next', 'anyone', 'eleven', 'much', 'call', 'therefore', 'interest', 'then', 'thru', 'themselves', 'hundred', 'was', 'sincere', 'empty', 'more', 'himself', 'elsewhere', 'mostly', 'on', 'fire', 'am', 'becoming', 'hereby', 'amongst', 'else', 'part', 'everywhere', 'too', 'herself', 'former', 'those', 'he', 'me', 'myself', 'made', 'twenty', 'these', 'bill', 'cant', 'us', 'until', 'besides', 'nevertheless', 'below', 'anywhere', 'nine', 'can', 'of', 'your', 'toward', 'my', 'something', 'and', 'whereafter', 'whenever', 'give', 'almost', 'wherever', 'is', 'describe', 'beforehand', 'herein', 'an', 'as', 'itself', 'at', 'have', 'in', 'seem', 'whence', 'ie', 'any', 'fill', 'again', 'hasnt', 'inc', 'thereby', 'thin', 'no', 'perhaps', 'latter', 'meanwhile', 'when', 'detail', 'same', 'wherein', 'beside', 'also', 'that', 'other', 'take', 'which', 'becomes', 'you', 'if', 'nobody', 'see', 'though', 'may', 'after', 'upon', 'most', 'hereupon', 'eight', 'but', 'serious', 'nothing', 'such', 'why', 'a', 'off', 'whereby', 'third', 'i', 'whole', 'noone', 'sometimes', 'well', 'amoungst', 'yours', 'their', 'rather', 'without', 'so', 'five', 'the', 'first', 'whereas', 'once']\n", + "\n", + "# Write your code below\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Additional Challenge for the Nerds\n", + "\n", + "We will learn Scikit-Learn in Module 3 which has built in the BoW feature. Try to use Scikit-Learn to generate the BoW for this challenge and check whether the output is the same as yours. You will need to do some googling to find out how to use Scikit-Learn to generate BoW.\n", + "\n", + "**Notes:**\n", + "\n", + "* To install Scikit-Learn, use `pip install sklearn`. \n", + "\n", + "* Scikit-Learn removes stop words by default. You don't need to manually remove stop words.\n", + "\n", + "* Scikit-Learn's output has slightly different format from the output example demonstrated above. It's ok, you don't need to convert the Scikit-Learn output.\n", + "\n", + "The Scikit-Learn output will look like below:\n", + "\n", + "```python\n", + "# BoW:\n", + "{u'love': 5, u'ironhack': 3, u'student': 6, u'is': 4, u'cool': 2, u'am': 0, u'at': 1}\n", + "\n", + "# term_freq:\n", + "[[0 0 1 1 1 0 0]\n", + " [0 0 0 1 0 1 0]\n", + " [1 1 0 1 0 0 1]]\n", + " ```" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.12" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +}