Text preprocessing
Text preprocessing is a fundamental and critical step in Natural Language Processing (NLP); it transforms raw unstructured text data into a format suitable for machine learning models.
This article systematically introduces the three core stages of text preprocessing: text cleaning, tokenization, and part-of-speech tagging.
Text Cleaning: Purifying Raw Text Data
Text cleaning is the first step of preprocessing, aimed at removing noisy data from text and improving the accuracy of subsequent processing.
Encoding Format Handling
Text from different sources may use different encoding formats (such as UTF-8, GBK, ASCII, etc.); unifying the encoding is the first task:
Example
Encoding Conversion Example
text
=
"sample text"
.
encode
(
'gbk'
)
Assume the original encoding is GBK
text
=
text.
decode
(
'gbk'
)
.
encode
(
'utf-8'
)
Convert to UTF-8
Solutions to Common Encoding Problems:
- Use
chardetLibrary automatically detects encoding - Unify conversion to UTF-8 encoding
- Handle characters that cannot be decoded (usually replace or ignore)
Special Character Handling
Different scenarios require handling different types of special characters:
| Character type | Handling Methods | Application scenarios |
|---|---|---|
| HTML tags | Remove with regular expressions | Web-crawled text |
| Emojis | Remove or convert to text descriptions | Social media analysis |
| Control characters | Filter out | All text processing |
| Special punctuation | Standardization | Text Normalization |
Example
import
re
Example of Removing HTML Tags
text
=
"
This is aHTMLText
"clean_text
=
re
.
sub
(
r
'<[^>]+>'
,
''
,
text
)
(
clean_text
)
Output: This is a piece of HTML text
Noise Data Removal
Depending on specific task requirements, you may need to:
- Remove irrelevant information (ads, copyright notices, etc.)
- Handle spelling errors (using spell-check libraries)
- Standardize numeric representation (e.g., unify "1000" as "1,000")
- Unify date formats ("2023-01-01" vs "01/01/2023")
Tokenization: Breaking Text into Basic Units
Tokenization is the process of splitting continuous text into meaningful language units (tokens); different languages require different tokenization methods.
English Tokenization Methods
English tokenization is relatively simple, mainly based on spaces and punctuation splitting:
Example
English tokenization using NLTK
from
nltk.
tokenize
import
word_tokenize
text
=
"Natural Language Processing is fascinating!"
tokens
=
word_tokenize
(
text
)
(
tokens
)
['Natural', 'Language', 'Processing', 'is', 'fascinating', '!']
Notes on English Tokenization:
- Handle abbreviations (e.g., "I'm" → "I" + "'m")
- Preserve or merge specific phrases (e.g., "New York" as one token)
- Handle hyphens ("state-of-the-art")
Chinese Tokenization Techniques
Chinese has no obvious word boundaries, making tokenization more complex. Main methods include:
- Dictionary-based Tokenization: Maximum matching method, shortest path method
- Statistical-based Tokenization: Sequence labeling methods such as HMM and CRF
- Deep learning-based Tokenization: Models such as BiLSTM-CRF and BERT
Example
Chinese tokenization using jieba
import
jieba
text
=
"Natural language processing is very interesting"
tokens
=
jieba.
lcut
(
text
)
(
tokens
)
['natural language', 'processing', 'very', 'interesting']
Subword Tokenization (Subword Tokenization)
Solves rare word and vocabulary expansion problems; common methods:
- Byte Pair Encoding (BPE): Build subwords by merging high-frequency character pairs
- WordPiece: Similar to BPE, but merges based on probability
- Unigram Language Model: Start from a large vocabulary and gradually remove low-probability subwords
Example
Example using HuggingFace's tokenizer
from
transformers
import
BertTokenizer
tokenizer
=
BertTokenizer.
from_pretrained
(
'bert-base-chinese'
)
tokens
=
tokenizer.
tokenize
(
"Natural language processing"
)
(
tokens
)
['Zi' (a Chinese character), 'Ran' (a Chinese character), 'Yu' (a Chinese character), 'Yan' (a Chinese character), 'Chu' (a Chinese character), 'Li' (a Chinese character)]
Comparison of Common Tokenization Tools
| Tool name | Supported Languages | Feature | Applicable scenarios |
|---|---|---|---|
| NLTK | Mainly English | Comprehensive features, average speed | Teaching, research |
| spaCy | Multilingual | Industrial-grade, fast | Production environment |
| jieba | Chinese | Simple to use, extensible dictionary | Chinese processing |
| Stanford CoreNLP | Multilingual | High accuracy, high resource consumption | Academic research |
| HuggingFace Tokenizers | Multilingual | Supports subword tokenization | Deep learning |
Part-of-Speech Tagging: Understanding the Grammatical Roles of Words
Part-of-Speech Tagging (Part-of-Speech Tagging) is the process of labeling each word in the tokenization results with its part-of-speech category.
The Concept of Part-of-Speech Tagging
Part-of-speech tagging helps to:
- Understand sentence structure
- Eliminate word sense ambiguity
- Support more advanced NLP tasks (such as syntactic parsing)
Common Part-of-Speech Tag Sets
Different languages and tools use different part-of-speech tagging systems:
Common English Penn Treebank tag set (partial):
- NN: Noun
- VB: Verb
- JJ: Adjective
- RB: Adverb
- PRP: Pronoun
Common Chinese ICTCLAS tag set (partial):
- n: Noun
- v: Verb
- a: Adjective
- d: Adverb
- r: Pronoun
Automatic Part-of-Speech Tagging Methods
- Rule-based methods: Tagging using hand-written rules
- Statistical methods: Models such as HMM and MaxEnt
- Deep learning based methods: Neural networks such as RNN and Transformer
Example
Part-of-speech tagging using spaCy
import
spacy
nlp
=
spacy.
load
(
"en_core_web_sm"
)
doc
=
nlp
(
"Natural Language Processing is fascinating!"
)
for
token
in
doc:
(
token
.
text
,
token
.
pos_
)
Output each word and its part-of-speech tag
Evaluation Metrics for Part-of-Speech Tagging:
- Accuracy
- Unknown word accuracy (OOV Accuracy)
- Confusion Matrix Analysis
Practical Suggestions
- Preprocessing Pipeline Order: Encoding handling → text cleaning → tokenization → part-of-speech tagging
- Principles for Tool Selection: Choose appropriate tools based on language, task requirements, and performance needs
- Custom Processing: Specific domains may require custom dictionaries or rules
- Performance optimization: For large-scale text, consider parallel processing or efficient tools