保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button We value your privacy We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies. Customise Reject All Accept All Customise Consent Preferences We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below. The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more NecessaryAlways Active Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search Data Science

Building Blocks: Text Pre-Processing

Key concepts and practical implementation Shashank Kapadia March 2, 20198 min read An image of pale code stretching across a black background Image via Pixabay In the last article of our series, we introduced the concept of Natural Language Processing. You can read it here, and now you probably want to try it yourself, right? Great! Without further ado, let’s dive into the building blocks for statistical natural language processing. In this article, we’ll introduce the key concepts, along with practical implementation in Python and the challenges to keep in mind at the time of application. The complete code is available as a Jupyter Notebook on GitHub.

Text normalization

Normalizing the text means converting it to a more convenient, standard form before performing turning it into features for higher-level modeling. Think of this step as converting human-readable language into a form that is machine-readable. The standard framework to normalize the text includes:

  1. Tokenization
  2. Stop words removal
  3. Morphological normalization
  4. Collocation

Data preprocessing consists of a number of steps, any number of which may or not apply to a given task. More generally, in this article we’ll discuss some predetermined body of text, and perform some basic transformative analysis that can be used for performing further, more meaningful natural language processing.[1] Learn this step by step with the interactive AI and Data Scientist roadmap.

Tokenization

Given a character sequence and a defined document unit (blurb of texts), tokenization is the task of chopping it up into pieces, called tokens , perhaps at the same time throwing away certain characters/words, such as punctuation [2]. Ordinarily, there are two types of tokenization:

  1. Word tokenization: Used to separate words via unique space character. Depending on the application, word tokenization may also tokenize multi-word expressions like New York. This is often times is closely tied to a process called Named Entity Recognition. Later in this tutorial, we will look at Collocation (Phrase) Modeling that helps address part of this challenge.
  2. Sentence tokenization/segmentation: Along with word tokenization, sentence segmentation is a crucial step in text processing. This is usually performed based on punctuations such as “.”, “?”, “!” as they tend to mark the sentence boundaries.

Challenges:

Implementation example: python

from nltk.tokenize import sent_tokenize, word_tokenize
#Sentence Tokenization
print ('Following is the list of sentences tokenized from the sample review\n')
sample_text = """The first time I ate here I honestly was not that impressed. I decided to wait a bit and give it another chance. 
I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and 
swiss burgers I had were honestly very good. The shakes were also tasty. Although Mad Mikes is still my favorite burger around, 
you can do a heck of a lot worse than Smashburger if you get a craving"""
tokenize_sentence = sent_tokenize(sample_text)
print (tokenize_sentence)
print ('---------------------------------------------------------\n')
print ('Following is the list of words tokenized from the sample review sentence\n')
tokenize_words = word_tokenize(tokenize_sentence[1])
print (tokenize_words)

Output: markup

Following is the list of sentences tokenized from the sample review['The first time I ate here I honestly was not that impressed.', 'I decided to wait a bit and give it another chance.', 'I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and \nswiss burgers I had were honestly very good.', 'The shakes were also tasty.', 'Although Mad Mikes is still my favorite burger around, \nyou can do a heck of a lot worse than Smashburger if you get a craving']---------------------------------------------------------Following is the list of words tokenized from the sample review sentence['I', 'decided', 'to', 'wait', 'a', 'bit', 'and', 'give', 'it', 'another', 'chance', '.']

Stop words removal

Often, a few ubiquitous words which would appear to be of little value in helping the purpose of analysis but increase the dimensionality of feature set are excluded from the vocabulary entirely as part of the stop words removal process. There are two considerations that usually motivate this removal.

  1. Irrelevance: Allows one to analyze only on content-bearing words. Stopwords, also called empty words because they generally do not bear much meaning, introduce noise in the analysis/modeling process.
  2. Dimension: Removing the stopwords also allows one to reduce the tokens in documents significantly, and thereby decreasing feature dimension.

Challenges: Converting all characters into lowercase letters before stopwords removal process can introduce ambiguity in the text, and sometimes entirely changing the meaning of it. For example, with the expressions “US citizen” will be viewed as “us citizen” or “IT scientist” as “it scientist”. Since both us and it are normally considered stop words, it would result in an inaccurate outcome. The strategy regarding the treatment of stopwords can thus be refined by identifying that “US” and “IT” are not pronouns in the above examples, through a part-of-speech tagging step. Implementation example: python

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize# define the language for stopwords removal
stopwords = set(stopwords.words("english"))
print ("""{0} stop words""".format(len(stopwords)))tokenize_words = word_tokenize(sample_text)
filtered_sample_text = [w for w in tokenize_words if not w in stopwords]print ('\nOriginal Text:')
print ('------------------\n')
print (sample_text)
print ('\n Filtered Text:')
print ('------------------\n')
print (' '.join(str(token) for token in filtered_sample_text))

Output: markup

179 stop wordsOriginal Text:------------------The first time I ate here I honestly was not that impressed. I decided to wait a bit and give it another chance. I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burgers I had were honestly very good. The shakes were also tasty. Although Mad Mikes is still my favorite burger around, you can do a heck of a lot worse than Smashburger if you get a craving Filtered Text:------------------The first time I ate I honestly impressed . I decided wait bit give another chance . I recently eaten couple times although I convinced pricing particularly point two mushroom swiss burgers I honestly good . The shakes also tasty . Although Mad Mikes still favorite burger around , heck lot worse Smashburger get craving

Morphological normalization

Morphology, in general, is the study of the way words are built up from smaller meaning-bearing units, morphomes. For example, dogs consists of two morphemes: dog and s. Two commonly used techniques for text normalization are:

  1. Stemming: The procedure aims to identify the stem of a word and use it in lieu of the word itself. The most popular algorithm for stemming English, and one that has repeatedly been shown to be empirically very effective, is Porter’s algorithm. The entire algorithm is too long and intricate to present here [3], but you can find details here.
  2. Lemmatization: This process refers to doing things correctly with the use of vocabulary and morphological analysis of words, typically aiming to remove inflectional endings only and to return the base or dictionary form of a word, which is known as the lemma.

If confronted with the tokensaw , stemming might return justs , whereas lemmatization would attempt to return eithersee orsaw depending on whether the use of the token was as a verb or a noun.[4] Implementation example: python

from nltk.stem import PorterStemmer
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
ps = PorterStemmer()
lemmatizer = WordNetLemmatizer()
tokenize_words = word_tokenize(sample_text)
stemmed_sample_text = []
for token in tokenize_words:
    stemmed_sample_text.append(ps.stem(token))
lemma_sample_text = []
for token in tokenize_words:
    lemma_sample_text.append(lemmatizer.lemmatize(token))
    
print ('\nOriginal Text:')
print ('------------------\n')
print (sample_text)
print ('\nFiltered Text: Stemming')
print ('------------------\n')
print (' '.join(str(token) for token in stemmed_sample_text))
print ('\nFiltered Text: Lemmatization')
print ('--------------------------------\n')
print (' '.join(str(token) for token in lemma_sample_text))

Output: markup

Original Text:------------------The first time I ate here I honestly was not that impressed. I decided to wait a bit and give it another chance. I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burgers I had were honestly very good. The shakes were also tasty. Although Mad Mikes is still my favorite burger around, you can do a heck of a lot worse than Smashburger if you get a craving.Filtered Text: Stemming:------------------the first time I ate here I honestli wa not that impress . I decid to wait a bit and give it anoth chanc . I have recent eaten there a coupl of time and although I am not convinc that the price is particularli on point the two mushroom and swiss burger I had were honestli veri good . the shake were also tasti . although mad mike is still my favorit burger around , you can do a heck of a lot wors than smashburg if you get a crave .Filtered Text: Lemmatization--------------------------------The first time I ate here I honestly wa not that impressed . I decided to wait a bit and give it another chance . I have recently eaten there a couple of time and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burger I had were honestly very good . The shake were also tasty . Although Mad Mikes is still my favorite burger around , you can do a heck of a lot worse than Smashburger if you get a craving .

Challenges: Often, full morphological analysis produces, at most, very modest benefits for analysis. Neither form of normalization improves language information performance in aggregate, both from relevance and dimensionality reduction standpoint — at least not for the following situations: Implementation example: python

from nltk.stem import PorterStemmer
words = ["operate", "operating", "operates", "operation", "operative", "operatives", "operational"]
ps = PorterStemmer()
for token in words:
    print (ps.stem(token))

Output: markup

operoperoperoperoperoperoper

As an example of what can go wrong, note that the Porter stemmer stems all of the following words to oper. However, since operate in its various forms is a common verb, we would expect to lose considerable precision [4]:

For cases like these, moving to using a lemmatizer would not completely fix the problem because particular inflectional forms are used in specific collocations. Getting better value from term normalization depends more on pragmatic issues of word use than on formal issues of linguistic morphology. [4] For all the codes used to generate above results, click here. And that’s it! Now, you know all about gradient descent, linear regression, and logistic regression.

Coming up..

In the next article, we’ll discuss the concept of collocation (phrase) modeling in detail and walk through its implementation together. Stay tuned, and keep learning!

References:

[1] A General Approach to Preprocessing Text Data — KDnuggets. https://www.kdnuggets.com/2017/12/general-approach-preprocessing-text-data.html [2] Tokenization — Stanford NLP Group. https://nlp.stanford.edu/IR-book/html/htmledition/tokenization-1.html [3] Text Mining in Bovine Diseases — ijcaonline.org. https://www.ijcaonline.org/volume6/number10/pxc3871454.pdf [4] Stemming and lemmatization — Stanford NLP Group. https://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html If you have any feedback, please reach out by messaging me on LinkedIn or shooting me an email (shmkapadia[at]gmail.com).

Register Now to Continue Reading

Unlock Towards Data Science with a Free Account

All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account


SK Written By

Shashank Kapadia

See all from Shashank Kapadia Data PreprocessingMachine LearningNLPPythonText Preprocessing Share This Article

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS

Related Articles

Implementing Linear Regression with Gradient Descent From Scratch

Artificial Intelligence Build a strong machine learning foundation by fully understanding and deriving gradient descent Marvin Lanhenke January 16, 20226 min read

Deploy Python Codes with Azure Functions

Machine Learning Azure Functions are code triggered events that scale well owing to their serverless capabilities. The triggering mechanisms are diverse -... lalitha raghavan January 30, 20213 min read

Determining the optimal Pokemon team for Pokemon Brilliant Diamond and Shining Pearl with Pulp

Use Linear Programming to be the very best, like no one ever was... Jamshaid Shahir, Ph.D October 24, 202110 min read

How to Set Up a Data Analytics Team and Project Ecosystem for Success

Data Science Apply these techniques to build a data analytics program that delivers solutions to meet end-users' needs Randy Runtsch February 14, 202111 min read

An Introductory Reinforcement Learning Project: Learning Tic-Tac-Toe via Self-Play Tabular...

Machine Learning In this project, I'll walk through an introductory project on tabular Q-learning. We'll train a simple RL agent to learn a Q-table for the... Ryan Rudes September 8, 20204 min read

Speed up your Pandas Processing with Swifter

Artificial Intelligence Don't let your data processing taking you too long Cornellius Wijaya July 4, 20204 min read

Why Every Data Team Needs a "Money Tree"

Data Science How this framework rallied my stakeholders behind my work Ryan Foley November 2, 20202 min read

How to Onboard New Data Analysts

Artificial Intelligence Tips to add value faster Vicky Yu April 11, 20213 min read

How to Use SubQueries in SQL

Data Science Learn how to make your SQL queries more flexible using subqueries and reduce code clutter Ivo Bernardo October 28, 20228 min read

Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close