<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yuan Shi on Medium]]></title>
        <description><![CDATA[Stories by Yuan Shi on Medium]]></description>
        <link>https://medium.com/@sy563105221?source=rss-505fc832d92a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iwgOwY2bXYufkKFsfZEp4Q.jpeg</url>
            <title>Stories by Yuan Shi on Medium</title>
            <link>https://medium.com/@sy563105221?source=rss-505fc832d92a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:37:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sy563105221/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Clean & Process Raw Text Data: A Beginner’s Guide with Examples]]></title>
            <link>https://medium.com/@sy563105221/clean-process-raw-text-data-a-beginners-guide-with-examples-68ec7d65fd8c?source=rss-505fc832d92a------2</link>
            <guid isPermaLink="false">https://medium.com/p/68ec7d65fd8c</guid>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[text-preprocessing]]></category>
            <dc:creator><![CDATA[Yuan Shi]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 22:05:11 GMT</pubDate>
            <atom:updated>2022-02-16T05:51:06.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WBNWr1CpmLQ6ZHqT" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Natural Language Processing (NLP) is becoming one of the most popular data science specialization in both academic setting and industry these days. In the past years I was lucky enough to have exposure &amp; work on both supervised and unsupervised learning NLP projects; I found those super interesting but can be challenging at the same time.</p><p>For folks new to NLP, analyzing unstructured text data can be a big challenge due to its unstructured form and non-numeric nature. Just like you would process and clean numeric data — a list of pre-processing is required to clean text data for more accuracy analytical results, regardless of what you would like to do with them (classification, text clustering, topic modeling, etc).</p><p>Today, I put up a text data processing guide and wish to share it to wider audiences on how to process text data. This guide is put together for beginners, and examples are created for demonstration purpose.</p><h3>Dataset</h3><p>When I think about how I would write this guide, I actually want to just put up some random text myself to avoid the trouble finding a good data source. However, when I started to put something random — I realized it may be hard for me to fake how dirty (unorganized) some real text data source can be. So, I decided to use this open source dataset: <strong>Coronavirus tweets NLP</strong> from Kaggle for this guide.</p><p><a href="https://www.kaggle.com/datatattle/covid-19-nlp-text-classification/version/1">Coronavirus tweets NLP - Text Classification</a></p><h3>Step-by-step Processing</h3><p>I will show how to process the text data step-by-step in Python, and I will also explain what each section of codes are doing (that’s what we data scientists do, right?) At the same time, I am assuming that readers have at least a basic understanding of Python and some experience with traditional Machine Learning.</p><h3>Load required packages &amp; preview of the data</h3><p>The first thing when working on a dataset is always to do a quick EDA, in this case, we identify which column contains the text data then we subset it for further use.</p><pre><strong># We all know what this is for :) </strong><br># Pandas - read csv as pandas dataframe<br>import pandas as pd<br>import numpy as np<br>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)</pre><pre><strong># gensim: simple_preprocess for easy tokenization &amp; convert to a python list;<br></strong># also contain a list of common stopwords<br>import gensim<br>import gensim.corpora as corpora<br>from gensim.utils import simple_preprocess<br>from gensim.parsing.preprocessing import STOPWORDS as swords</pre><pre><strong>#nltk Lemmatize and stemmer, for lemmatization and stem, I will talk about it later<br></strong>import nltk<br>from nltk.stem import WordNetLemmatizer<br>from nltk.stem.porter import PorterStemmer<br>from nltk.stem.porter import *</pre><pre><strong># You might need to run the next two line if you don&#39;t have those come with your NLTK package</strong></pre><pre>#nltk.download(&#39;wordnet&#39;)<br>#nltk.download(&#39;stopwords&#39;)<br>from nltk.corpus import stopwords as st<br>from nltk.corpus import wordnet<br>from nltk.corpus import stopwords</pre><pre><strong># read in data<br></strong>tweet_data = pd.read_csv(&#39;Corona_NLP_train.csv&#39;, encoding=&#39;latin1&#39;)</pre><pre><strong># subset text colum, as we only need this column<br></strong>covid_tweet = tweet_data[&#39;OriginalTweet&#39;]</pre><pre><strong># quick preview<br></strong>covid_tweet[3]</pre><p>Let’s use the 3rd tweet as an example since it is pretty dirty :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4cmpkZrXDoNv-jPjR_20A.png" /><figcaption>Preview of 3rd tweet</figcaption></figure><h4>Original:</h4><p>“My food stock is not the only one which is empty…\r\r\n\r\r\nPLEASE, don’t panic, THERE WILL BE ENOUGH FOOD FOR EVERYONE if you do not take more than you need. \r\r\nStay calm, stay safe.\r\r\n\r\r\n#COVID19france #COVID_19 #COVID19 #coronavirus #confinement #Confinementotal #ConfinementGeneral <a href="https://t.co/zrlG0Z520j%22">https://t.co/zrlG0Z520j&quot;</a></p><h3>1. Tokenization</h3><p>Generally speaking, tokenization means:</p><ul><li>Remove punctuations &amp; special characters</li><li>Break down sentence into a list of vocabularies (it is called tokens), and store them in a data structure like list</li><li>All letters will be lower-cased</li></ul><pre>data = covid_tweet.values.tolist()</pre><pre><strong># Remove Emails, web links<br></strong>data = [re.sub(&#39;\S*@\S*\s?&#39;, &#39;&#39;, sent) for sent in data]</pre><pre><strong># Remove new line characters<br></strong>data = [re.sub(&#39;\s+&#39;, &#39; &#39;, sent) for sent in data]</pre><pre><strong># Remove distracting single quotes<br></strong>data = [re.sub(&quot;\&#39;&quot;, &#39;&#39;, sent) for sent in data]</pre><pre><strong>#Gensim simple_preprocess function can be your friend with tokenization<br></strong>def sent_to_words(sentences):<br>    for sentence in sentences:<br>        yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))  # deacc=True removes punctuations</pre><pre>data_words = list(sent_to_words(data))</pre><pre>print(data_words[:3])</pre><p><strong>After Tokenization:</strong></p><pre><strong>Output:<br></strong>[[&#39;https&#39;, &#39;co&#39;, &#39;ifz&#39;, &#39;fan&#39;, &#39;pa&#39;, &#39;and&#39;, &#39;https&#39;, &#39;co&#39;, &#39;xx&#39;, &#39;ghgfzcc&#39;, &#39;and&#39;, &#39;https&#39;, &#39;co&#39;, &#39;nlzdxno&#39;], [&#39;advice&#39;, &#39;talk&#39;, &#39;to&#39;, &#39;your&#39;, &#39;neighbours&#39;, &#39;family&#39;, &#39;to&#39;, &#39;exchange&#39;, &#39;phone&#39;, &#39;numbers&#39;, &#39;create&#39;, &#39;contact&#39;, &#39;list&#39;, &#39;with&#39;, &#39;phone&#39;, &#39;numbers&#39;, &#39;of&#39;, &#39;neighbours&#39;, &#39;schools&#39;, &#39;employer&#39;, &#39;chemist&#39;, &#39;gp&#39;, &#39;set&#39;, &#39;up&#39;, &#39;online&#39;, &#39;shopping&#39;, &#39;accounts&#39;, &#39;if&#39;, &#39;poss&#39;, &#39;adequate&#39;, &#39;supplies&#39;, &#39;of&#39;, &#39;regular&#39;, &#39;meds&#39;, &#39;but&#39;, &#39;not&#39;, &#39;over&#39;, &#39;order&#39;], [&#39;coronavirus&#39;, &#39;australia&#39;, &#39;woolworths&#39;, &#39;to&#39;, &#39;give&#39;, &#39;elderly&#39;, &#39;disabled&#39;, &#39;dedicated&#39;, &#39;shopping&#39;, &#39;hours&#39;, &#39;amid&#39;, &#39;covid&#39;, &#39;outbreak&#39;, &#39;https&#39;, &#39;co&#39;, &#39;binca&#39;, &#39;vp&#39;]]</pre><h3>2. Remove Stopwords</h3><p>Stopwords in NLP means words that doesn’t really have any meanings, some common examples are: as, if, what, for, to, and, but. You can probably guess, a lot of prepositions are stopwords since they don’t really have any meanings, or their meaning is too abstract and cannot infer any events.</p><pre><strong># Gensim stopwords list<br></strong>stop_words = st.words(&#39;english&#39;)</pre><pre><strong># Expand by adding NLTK stopwords list<br></strong>stop_words.append(stopwords.words(&#39;english&#39;))</pre><pre><strong>### extend stopwords by your choices, I think it&#39;s ok to add &#39;https&#39;, &#39;dont&#39;, and &#39;co&#39; to the stopword list since they means nothing<br></strong>stop_words.extend([&#39;https&#39;, &#39;co&#39;, &#39;dont&#39;] + list(swords))</pre><pre><strong># Put that in a function<br></strong>def remove_stopwords(texts):<br>    return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]</pre><p>After stopwords are removed:</p><pre># Remove Stop Words<br>data_words_nostops = remove_stopwords(data_words)<br>data_words_nostops[3]</pre><pre><strong>outputs:</strong><br>[&#39;food&#39;,<br> &#39;stock&#39;,<br> &#39;dont&#39;,<br> &#39;panic&#39;,<br> &#39;food&#39;,<br> &#39;need&#39;,<br> &#39;stay&#39;,<br> &#39;calm&#39;,<br> &#39;stay&#39;,<br> &#39;safe&#39;,<br> &#39;covid&#39;,<br> &#39;france&#39;,<br> &#39;covid_&#39;,<br> &#39;covid&#39;,<br> &#39;coronavirus&#39;,<br> &#39;confinement&#39;,<br> &#39;confinementotal&#39;,<br> &#39;zrlg&#39;]</pre><p>Now the words are a lot more meaningful but a lot less distracting, right?</p><h3>3. Part-of-speech tagging &amp; Lemmatization</h3><p>Lemmatization means: convert a word to its ‘dictionary form’, aka a lemma. An example could be converting ‘playing to play’, ‘plays to play’, ‘played to play’. Another example is: ‘feet to foot’, ‘cats to cat’.</p><p>In English, we use a lot of form of vocab for verbs and nouns to represent different tense as well plural and singular. But the computer doesn’t understand this, when it reads ‘plays’, it will be different as ‘play’. Don’t believe me? Here is a simple test:</p><pre>&#39;plays&#39; == &#39;play&#39;</pre><pre>Outputs:<br>False</pre><p>But here comes the question — Lemmatization needs to be applied on both verbs, nouns, etc. How does the computer now a token is a verb or a noun? The solution is called ‘Part-of-speech’ tagging, which is used to identify what kind of vocabulary a token is.</p><p>Now you understand what lemmatization is and part-of-speech it, here is how you can do this in python (btw, this step is time-consuming, if you just want to test it use a smaller dataset is helpful):</p><pre>def get_wordnet_pos(word):<br>    tag = nltk.pos_tag([word])[0][1][0].upper()<br>    tag_dict = {&quot;J&quot;: wordnet.ADJ,<br>                &quot;N&quot;: wordnet.NOUN,<br>                &quot;V&quot;: wordnet.VERB,<br>                &quot;R&quot;: wordnet.ADV}</pre><pre>return tag_dict.get(tag, wordnet.NOUN)</pre><pre><strong># Take the POS tag and use NLTK lemmatizer to apply lemmatization<br></strong>def lemmatize(texts):<br>    return [[WordNetLemmatizer().lemmatize(word, pos=get_wordnet_pos(word)) for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]</pre><p>After lemmatization:</p><pre><strong># lemmatize</strong><br>data_lemmatized = lemmatize(data_words_nostops)<br>print(data_lemmatized[3])</pre><pre><strong>Outputs:<br></strong>[[&#39;food&#39;],<br> [&#39;stock&#39;],<br> [&#39;panic&#39;],<br> [&#39;food&#39;],<br> [&#39;need&#39;],<br> [&#39;stay&#39;],<br> [&#39;calm&#39;],<br> [&#39;stay&#39;],<br> [&#39;safe&#39;],<br> [&#39;covid&#39;],<br> [&#39;france&#39;],<br> [&#39;covid_&#39;],<br> [&#39;covid&#39;],<br> [&#39;coronavirus&#39;],<br> [&#39;confinement&#39;],<br> [&#39;confinementotal&#39;],<br> [&#39;zrlg&#39;]]</pre><h3>4. (Optional) Quick Review, Expand stopwords, and/or Stem</h3><p>After lemmatization, in most cases, your text is pretty much clean and can be used for analytical purpose. To further clean your text data, it’s always a good idea to review your results and see what additional needs to be done.</p><p>After a quick review, we can see that ‘covid’ and ‘covid_’ both exist but they are just same words; so it’s good to just convert ‘covid_’ to ‘covid’ to keep it consistent.</p><pre><strong># replace &#39;covid_&#39; with &#39;covid&#39;</strong><br>def self_clean(texts):<br>    return [[word.replace(&#39;covid_&#39;, &#39;covid&#39;) for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]</pre><pre>data_lemmatized_cleaned = self_clean(data_lemmatized)<br>data_lemmatized_cleaned</pre><pre>Outputs:<br>[[&#39;food&#39;],<br> [&#39;stock&#39;],<br> [&#39;panic&#39;],<br> [&#39;food&#39;],<br> [&#39;need&#39;],<br> [&#39;stay&#39;],<br> [&#39;calm&#39;],<br> [&#39;stay&#39;],<br> [&#39;safe&#39;],<br> [&#39;covid&#39;],<br> [&#39;france&#39;],<br> [&#39;covid&#39;],<br> [&#39;covid&#39;],<br> [&#39;coronavirus&#39;],<br> [&#39;confinement&#39;],<br> [&#39;confinementotal&#39;],<br> [&#39;zrlg&#39;]]</pre><p><strong>Stem </strong>means words are reduced to their root form. Sometimes it may make words hard to read by human, and can be hard to interpret the results; be careful with this technique.</p><p>Here is what we have after applying stemming:</p><pre><strong># use stemmer from NLTK package</strong><br>def stemming(texts):<br>    return [[PorterStemmer().stem(word) for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]</pre><pre>print(stemming(data_lemmatized_cleaned)[3])</pre><pre>Output:<br>[[&#39;food&#39;],<br> [&#39;stock&#39;],<br> [&#39;dont&#39;],<br> [&#39;panic&#39;],<br> [&#39;food&#39;],<br> [&#39;need&#39;],<br> [&#39;stay&#39;],<br> [&#39;calm&#39;],<br> [&#39;stay&#39;],<br> [&#39;safe&#39;],<br> [&#39;covid&#39;],<br> [&#39;franc&#39;],<br> [&#39;covid&#39;],<br> [&#39;covid&#39;],<br> [&#39;coronaviru&#39;],<br> [&#39;confin&#39;],<br> [&#39;confinementot&#39;],<br> [&#39;zrlg&#39;]]</pre><p>Thanks for reading! This will mark the end of our journey.</p><p>These common used techniques can be used to clean your text data and make your text mining analysis easier. Remember, we are from here:</p><p>“My food stock is not the only one which is empty…\r\r\n\r\r\nPLEASE, don’t panic, THERE WILL BE ENOUGH FOOD FOR EVERYONE if you do not take more than you need. \r\r\nStay calm, stay safe.\r\r\n\r\r\n#COVID19france #COVID_19 #COVID19 #coronavirus #confinement #Confinementotal #ConfinementGeneral <a href="https://t.co/zrlG0Z520j%22">https://t.co/zrlG0Z520j&quot;</a></p><p>to here:</p><pre>[[&#39;food&#39;],<br> [&#39;stock&#39;],<br> [&#39;panic&#39;],<br> [&#39;food&#39;],<br> [&#39;need&#39;],<br> [&#39;stay&#39;],<br> [&#39;calm&#39;],<br> [&#39;stay&#39;],<br> [&#39;safe&#39;],<br> [&#39;covid&#39;],<br> [&#39;france&#39;],<br> [&#39;covid&#39;],<br> [&#39;covid&#39;],<br> [&#39;coronavirus&#39;],<br> [&#39;confinement&#39;],<br> [&#39;confinementotal&#39;],<br> [&#39;zrlg&#39;]]</pre><p>If you are interested in more advanced NLP learning, I will consider to write about how text is processed to numeric term through TF-IDF or Bag-of-words; and how classification or clustering algorithm is able to use results from these techniques. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68ec7d65fd8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>