{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Our Task: Find similar company names\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have completed our Python Primer, let's try to complete a real task, while at the same time trying to practice loops, iterations, and other Python functionality that we studied." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Your high level task\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You are given a list of names. You know that the same entity in the list has different representations. You want to find duplicate companies in the data.\n", "\n", "As a concrete example, open the file under `data/restaurant-names.txt`. This contains a list of restaurant names, extracted from the [NYC Restaurant inspection data set](https://data.cityofnewyork.us/Health/DOHMH-New-York-City-Restaurant-Inspection-Results/xx67-kt59/data) (available online). The Department of Health has been doing a decent, but not perfect, job in recording the company names. Therefore, the same restaurant appears under different names. **Your task is to find \"almost duplicate\" entries in order to decide whether they correspond to the same business.**\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!head -10 ../data/restaurant-names.txt" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!tail -5 ../data/restaurant-names.txt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matching Company Names" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Quite often, in our data, we have entries represented as strings that refer to the same entity but have different string representations (e.g., McDonald's vs McDonalds vs McDonald‎). We want to write code that will help in the task of finding such similar entries in our data.\n", "\n", "Our task can be broken in the following tasks:\n", "* **Step 1**: Read the data from a file into a list of strings in memory. We have a data set under the `data` folder: The list of unique restaurant names from the NYC Restaurant Inspection dataset (`data/restaurant-names.txt`). We need to write Python code that will read th file and return a list of strings that are the company names.\n", "* **Step 2**: We will then need to figure out how to compare two strings and find their similarity. For that, we will write a function that takes as input **two** strings, and returns back their similarities. We will explore multiple ways of writing that function, using various library functions.\n", "* **Step 3**: We will need to write a function that takes as input a company name, and returns back a list of matching company names, together with their similarity. Ideally, we would like to also sort the list based on the similarity (highest similarity metrics on top). As part of our learning process, we will use the _list comprehension_ approach to create the list. We will also use tuples as the elements of the list, so that the list contain elements such as `[(\"McDonalds\", 0.88), (\"McDonald's\", 0.81),....]`.\n", "* **Step 4**: In the final step, we will just perform the similarity computation across all companies in the dataset." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## STEP 1: Read the list of names from a file and create a list of names" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# STEP 1: Read the list of names from a file and create a list of names\n", "filename = \"../data/restaurant-names.txt\"\n", "\n", "# We open the filename for reading\n", "f = ...\n", "# Read the file into memory\n", "content = ...\n", "# Content is a big string, with one restaurant per line\n", "# so we split it into lines and create a list with the restaurant names\n", "restaurants = ..." ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "### Solution" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "# STEP 1: Read the list of names from a file and create a list of names\n", "filename = \"../data/restaurant-names.txt\"\n", "\n", "# We open the filename for reading\n", "f = open(filename, \"r\")\n", "# Read the file into memory\n", "content = f.read()\n", "# Content is a big string, with one restaurant per line\n", "# so we split it into lines and create a list with the restaurant names\n", "restaurants = content.split(\"\\n\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "len(restaurants)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "restaurants" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## STEP 2: Implement the similarity function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Computing the similarity between two strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many ways that we can calculate the similarity between two strings. For our case, we will focus on a few similarity metrics that already have implementations in Python. \n", "\n", "#### Some commonly used similarity metrics\n", "\n", "* [Sequence matching](https://docs.python.org/3.6/library/difflib.html) (part of standard Python) ([example](http://stackoverflow.com/questions/17388213/find-the-similarity-percent-between-two-strings))\n", "* [Edit distance](https://en.wikipedia.org/wiki/Edit_distance) ([Python Jellyfish Library](https://github.com/jamesturk/jellyfish))\n", "* [N-gram distance](http://pythonhosted.org/ngram/tutorial.html#comparing-and-searching-strings)\n", "\n", "\n", "#### STEP 2.a: Let's install the libraries..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Edit distance\n", "!sudo -H pip3 install -U jellyfish" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Ngram\n", "!sudo -H pip3 install -U ngram" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### STEP 2.b: Now let's test our similarity functions with various examples\n", "\n", "Once we have installed the necessary libraries for our project, we proceed to `import` them and test the functions." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import jellyfish" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Edit Distance\n", "\n", "From Wikipedia:\n", "\n", "The [edit distance](https://en.wikipedia.org/wiki/Edit_distance) _ is a way of quantifying how dissimilar two strings (e.g., words) are to one another by counting the minimum number of operations required to transform one string into the other._. \n", "\n", "The Levenshtein distance between \"kitten\" and \"sitting\" is 3. A minimal edit script that transforms the former into the latter is:\n", "\n", "* kitten → sitten (substitution of \"s\" for \"k\")\n", "* sitten → sittin (substitution of \"i\" for \"e\")\n", "* sittin → sitting (insertion of \"g\" at the end)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.levenshtein_distance(\"kitten\", \"sitting\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's try a few more examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.levenshtein_distance(\"Ipeirotis\", \"Iperiotos\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.levenshtein_distance(\"Starbucks\", \"Starbacks\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.levenshtein_distance(\"Starbucks\", \"Starbuck\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.levenshtein_distance(\"Starbucks\", \"Wendys\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Demerau Levenshtein distance\n", "\n", "The Demerau Levenshtein distance also allows for transposition of two adjacent characters." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.levenshtein_distance(\"Ipeirotis\", \"Iperiotis\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.damerau_levenshtein_distance(\"Ipeirotis\", \"Iperiotis\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.damerau_levenshtein_distance(\"Starbucks\", \"Starbucsk\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.levenshtein_distance(\"Starbucks\", \"Starbucsk\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###### Jaro–Winkler distance\n", "\n", "[Jaro–Winkler distance](https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance) is a string metric for measuring the edit distance between two sequences. Informally, the **Jaro** distance between two words is the minimum number of single-character transpositions required to change one word into the other; the **Jaro–Winkler** distance gives more favourable ratings to strings that match from the beginning.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.jaro_winkler(\"Starbucks\", \"Starbarbr\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.jaro_winkler(\"Starbucks\", \"Milwbucks\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Soundex\n", "\n", "[Soundex](https://en.wikipedia.org/wiki/Soundex) is a phonetic algorithm for indexing names by sound, as pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling. \n", "\n", "Using this algorithm, both \"Robert\" and \"Rupert\" return the same string \"R163\" while \"Rubin\" yields \"R150\". \"Ashcraft\" and \"Ashcroft\" both yield \"A261\". \"Tymczak\" yields \"T522\" not \"T520\" (the chars 'z' and 'k' in the name are coded as 2 twice since a vowel lies in between them). \"Pfister\" yields \"P236\" not \"P123\" (the first two letters have the same number and are coded once as 'P')." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.soundex(\"Robert\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.soundex(\"Rupert\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.soundex(\"Ashcroft\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.soundex(\"Ashcraft\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.soundex(\"Papadopoylis\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jellyfish.soundex(\"Papadopoulos\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Ngrams\n", "\n", "With the n-gram similarity score, we split the word into sequences of n consecutive characters (n-grams) and then compare the sets of n-grams between the two words. For example, the name \"Panos\" has the following 2-grams: \"Pa\", \"an\", \"no\", \"os\". (We can also add \"#P\" and \"s#\" if we want to capture the prefix and suffixes.) Strings that share a large number of q-grams are often similar." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import ngram" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ngram.NGram.compare(\"Ipeirotis\", \"Iperotis\", N=2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ngram.NGram.compare(\"Ipeirotis\", \"Iperotis\", N=1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ngram.NGram.compare(\"New York University\", \"New York Universty\", N=2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ngram.NGram.compare(\"New York University\", \"University of New York\", N=1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ngram.NGram.compare(\"New York University\", \"Columbia Universty\", N=2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Task 1: Create a function that takes as input two strings and returns their similarity\n", "\n", "Given the experience with the metrics above, we want now to create a function that takes as input a string and returns their similarity. Our key requirement is for the similarity metric to be between 0 and 1, with 0 meaning no similarity, and 1 corresponding to identical strings. Some of the similarity functions above would fit right in, others will need some work. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import ngram\n", "import jellyfish\n", "\n", "\n", "def normalized_similarity_edit_distance(str1, str2):\n", " # Compute the similarity between str1 and str2\n", " distance = ...\n", " # Normalize\n", " normalized = ...\n", " # Return the result\n", " return ..." ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "### Solution" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "# For n-gram similarity it is very simple, we just return the result\n", "import ngram\n", "\n", "\n", "def computeSimilarity_ngram(str1, str2, n=3):\n", " similarity = ngram.NGram.compare(str1, str2, N=n)\n", " return similarity" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "computeSimilarity_ngram(\"New York University\", \"New York Univ\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "computeSimilarity_ngram(\"New York University\", \"New York Univ\", n=2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "computeSimilarity_ngram(\"New York University\", \"New York Univ\", n=4)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "computeSimilarity_ngram(\"New York University\", \"Columbia Univ\", n=2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "# For edit distance\n", "import jellyfish\n", "\n", "\n", "def computeSimilarity_editdistance(str1, str2):\n", " # Compute the maximum length of the two strings, to normalize our distance\n", " maxlength = max(len(str1), len(str2))\n", " # Compute the edit distance between two strings\n", " distance = jellyfish.levenshtein_distance(str1, str2)\n", " similarity = 1 - distance / maxlength\n", " return similarity\n", "\n", "\n", "computeSimilarity_editdistance(\"New York University\", \"New York Univ\")\n", "computeSimilarity_editdistance(\"New York University\", \"Columbia Univ\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "# For soundex\n", "import jellyfish\n", "\n", "\n", "def computeSimilarity_soundex(str1, str2):\n", " soundex1 = jellyfish.soundex(str1)\n", " soundex2 = jellyfish.soundex(str2)\n", " if soundex1 == soundex2:\n", " return 1.0\n", " else:\n", " return 0.0\n", "\n", "\n", "computeSimilarity_soundex(\"New York University\", \"New York Univ\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Task 2: Modify the functions above to allow for various similarity calculation methods.\n", "\n", "We will now up our game, and return back the results of the comparison using various methods. The `method` parameter defines the metric that we will use" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def computeSimilarity(str1, str2, method):\n", " # The function should check the method\n", " # and then call the appropriate similarity function\n", " # what we implemented above and return the\n", " # corresponding similarity value\n", " return ..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Getting closer to a real setting, we can now\n", "# compute all the similarity metrics and return them\n", "# all. Perhaps even compute an average value\n", "def computeSimilarity(str1, str2):\n", " # We return a dictionary with all the metrics\n", " return {\"ngram2\": ..., \"soundex\": ...}" ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "### Solution" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "def computeSimilarity(str1, str2, method):\n", " if method == \"ngram2\":\n", " return computeSimilarity_ngram(str1, str2, n=2)\n", " elif method == \"ngram3\":\n", " return computeSimilarity_ngram(str1, str2, n=3)\n", " elif method == \"ngram4\":\n", " return computeSimilarity_ngram(str1, str2, n=4)\n", " elif method == \"edit_distance\":\n", " return computeSimilarity_editdistance(str1, str2)\n", " elif method == \"soundex\":\n", " return computeSimilarity_soundex(str1, str2)\n", " else:\n", " return None" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "computeSimilarity(\"New York University\", \"New York Univ\", \"ngram3\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "computeSimilarity(\"New York University\", \"New York Univ\", \"edit_distance\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "# Most of the time we are going to compute all similarity metrics\n", "# and return back a dictionary with all the metrics\n", "def computeSimilarity(str1, str2):\n", " results = {\n", " \"ngram2\": computeSimilarity_ngram(str1, str2, n=2),\n", " \"ngram3\": computeSimilarity_ngram(str1, str2, n=3),\n", " \"ngram4\": computeSimilarity_ngram(str1, str2, n=4),\n", " \"edit_distance\": computeSimilarity_editdistance(str1, str2),\n", " \"soundex\": computeSimilarity_soundex(str1, str2),\n", " }\n", " # Arbitrarily, compute a similarity metric as the average of all\n", " results[\"average\"] = sum(results.values()) / len(results)\n", " # Similarly arbitrarily, we can compute our own metric, by mixing\n", " # the various metrics in our own way.\n", " results[\"custom\"] = (\n", " results[\"ngram3\"] + 2.5 * results[\"edit_distance\"] + 0.5 * results[\"soundex\"]\n", " ) / 4\n", " return results" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "computeSimilarity(\"New York University\", \"New York Univ\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## STEP 3: Compute similarity of a company against a list of company names" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We now create a function that accepts a company name and a list of companies, and computes their similarity. This part will get us to exercise our for-loops, and also illustrate how we can use lists and tuples." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Sorting a list of tuples**:_This part is a little bit advanced for now, so I will just give the code below. (Solution taken from http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples). Here is a small example below, which we will reuse in our function:_" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data = [(\"Panos\", 0.5), (\"Peter\", 0.8), (\"Pan\", 0.8)]\n", "\n", "# This code sorts the list \"data\", by using the second element\n", "# of each tuple as the sorting key, and sorts things in reverse order\n", "data.sort(\n", " key=lambda tupl: tupl[1], reverse=True\n", ") # sorts in place, in descending order, based on the second element of the tuple\n", "print(data)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# STEP 3: We now create a function that accepts a company name\n", "# and a list of companies, and computes their similarity\n", "# We have a 'top' parameter (by default set to be 5)\n", "# that restricts the results to only the \"top\" most similar\n", "# string pairs. We also define a parameter \"method\" that defines\n", "# what is the similarity method that we want to use. We also define a\n", "# similarity threshold for keeping only results with sufficient similarity\n", "\n", "\n", "def companySimilarity(query, companyList, top=5, method=\"average\", sim_threshold=0.25):\n", " ..." ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "### Solution" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "# STEP 3: We now create a function that accepts a company name\n", "# and a list of companies, and computes their similarity\n", "# We have a 'top' parameter (by default set to be 5)\n", "# that restricts the results to only the most similar\n", "# string pairs. We also define a parameter \"method\" that defines\n", "# what is the similarity method that we want to use. We also define a\n", "# similarity threshold for keeping only results with sufficient similarity\n", "\n", "\n", "def companySimilarity(query, companyList, top=5, method=\"average\", sim_threshold=0.25):\n", " # We will use a list to store the similar matches\n", " results = []\n", "\n", " # Go through all the restaurants\n", " for c in companyList:\n", " # We compute the similarities (all metrics)\n", " # between the string \"query\" and the string \"c\"\n", " # which is the variable that iterates over the list \"companyList\"\n", " similarities = computeSimilarity(query, c)\n", " # If the ngram similarity is above 0.25\n", " if similarities[method] > sim_threshold:\n", " # Add in results the matching restaurant name r\n", " # and the similarity\n", " results.append((c, similarities[method]))\n", "\n", " # This list contains the matches. The list contains a list\n", " # of tuples (company name, similarity)\n", " # We sort in decreasing order of similarity\n", " results.sort(key=lambda tupl: tupl[1], reverse=True)\n", "\n", " # We return only the top results\n", " return results[:top]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "query = \"MACDONALDS\"\n", "companySimilarity(query, restaurants, top=5, method=\"ngram3\", sim_threshold=0.25)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "query = \"MACDONALDS\"\n", "companySimilarity(query, restaurants, top=5, method=\"average\", sim_threshold=0.25)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "query = \"STARBUCKS\"\n", "companySimilarity(query, restaurants, top=5, method=\"ngram3\", sim_threshold=0.25)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "query = \"STARBUCKS\"\n", "companySimilarity(query, restaurants, top=20, method=\"average\", sim_threshold=0.25)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 4: Perform the similarity computation across all companies in the dataset." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We are almost done. We now just go through all the companies in the list\n", " and we call the `companySimilarity` function that computes the similar company names\n", " _for all the companies in the list_." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# STEP 4: We are almost done. We now just go through all the companies in the list\n", "# and we call the companySimilarity function that computes the similar company names\n", "# for all the companies in the list. We store the results in a dictionary, with the\n", "# key being the company name, and the value being a \"list of tuples\" with the\n", "# similar company names and the corresponding similarity value.\n", "\n", "# Your code here" ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "### Solution" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "# STEP 4: We are almost done. We now just go through all the companies in the list\n", "# and we call the companySimilarity function that computes the similar company names\n", "# for all the companies in the list. We store the results in a dictionary, with the\n", "# key being the company name, and the value being a \"list of tuples\" with the\n", "# similar company names and the corresponding similarity value.\n", "\n", "\n", "# The matches counter is just to stop the computation quickly\n", "# after we have showed enough matches\n", "matches = 0\n", "stop_after = 20\n", "\n", "for q in restaurants:\n", " results = companySimilarity(\n", " query=q, # the name of the restaurant that we use are query\n", " companyList=restaurants, # the list of restaurants\n", " top=6, # the number of matches that we want to get\n", " method=\"average\", # which similarity method to use\n", " sim_threshold=0.4, # the similarity threshold\n", " )\n", " # We will print only non-identical matches (remember the top\n", " # match is the restaurant matching with itself)\n", " if len(results) > 1:\n", " for r in results[1:]:\n", " print(f\"{q}\\t===>\\t{r[0]}\\t{r[1]:2.3%}\")\n", " matches = matches + 1\n", " if matches > stop_after:\n", " break # We stop after a few illustrative matches" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.8.2" } }, "nbformat": 4, "nbformat_minor": 1 }