{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lab 6 (solved)\n", "* How to count the number of words in a string?\n", "* How to count number of different words in a string?" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "#My String\n", "phrase=\"I want to know how many words I have in this phrase\"" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "#convert string into list\n", "words=phrase.split()" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# count number of elements in the list \n", "len(words)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "# Count the number of each different \n", "countWords = dict()\n", "for word in words:\n", " if word in countWords:\n", " countWords[word] += 1\n", " else:\n", " countWords[word] = 1" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'I': 2,\n", " 'want': 1,\n", " 'to': 1,\n", " 'know': 1,\n", " 'how': 1,\n", " 'many': 1,\n", " 'words': 1,\n", " 'have': 1,\n", " 'in': 1,\n", " 'this': 1,\n", " 'phrase': 1}" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "countWords" ] }, { "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.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }