Data processing tools
Natural language processing (NLP) is an important branch of artificial intelligence, and data processing is the key to the success of NLP projects.
This article will systematically introduce the essential toolset for the full NLP data processing workflow, covering core stages such as data cleaning, numerical computation, feature engineering, machine learning, and visualization.

Pandas: Data Cleaning and Preprocessing
Pandas core data structures
Pandas provides two main data structures, which are the cornerstone of NLP data processing:
| Data Structure | Feature | NLP application scenarios |
|---|---|---|
| Series | One-dimensional labeled array | Stores a single text feature column |
| DataFrame | Two-dimensional tabular structure | Stores the entire text dataset |
Common text processing operations
Example
import
pandas
as
pd
Create sample data
data
=
{
'text'
:
[
'Hello World!'
,
'NLP is amazing'
,
'Python 3.8'
]
,
'label'
:
[
1
,
0
,
1
]
}
df
=
pd.
DataFrame
(
data
)
1. Text cleaning
df
[
'clean_text'
]
=
df
[
'text'
]
.
str
.
lower
(
)
Convert to lowercase
df
[
'clean_text'
]
=
df
[
'clean_text'
]
.
str
.
replace
(
'[^\w\s]'
,
''
)
Remove punctuation
2. Tokenization
df
[
'tokens'
]
=
df
[
'clean_text'
]
.
str
.
split
(
)
Split by whitespace
3. Word frequency counting
word_counts
=
df
[
'tokens'
]
.
explode
(
)
.
value_counts
(
)
(
word_counts
)
Advanced text processing techniques
- Regular expression filtering:
df['text'].str.contains(r'\bNLP\b') - Stop word removal: combined with the NLTK or spaCy libraries
- Handling Missing Values:
df.dropna()ordf.fillna('UNK')
NumPy: Efficient Numerical Computation
Core Features
NumPy provides efficient numerical computing capabilities for NLP:
- Multidimensional Arrays: storing word vectors and embedding matrices
- Broadcasting mechanism: efficiently performing element-wise operations
- Linear Algebra: matrix factorization and similarity computation
Typical application example
Example
import
numpy
as
np
Create a word vector matrix (3 words, 5 dimensions each)
word_vectors
=
np.
array
(
[
[
0.1
,
0.2
,
0.3
,
0.4
,
0.5
]
,
Word 1
[
0.6
,
0.7
,
0.8
,
0.9
,
1.0
]
,
Word 2
[
1.1
,
1.2
,
1.3
,
1.4
,
1.5
]
Word 3
]
)
Compute cosine similarity
def
cosine_similarity
(
a
,
b
)
:
return
np.
dot
(
a
,
b
)
/
(
np.
linalg
.
norm
(
a
)
(
np.
linalg
.
norm
(
b
)
)
Compute the similarity of the first two words
sim
=
cosine_similarity
(
word_vectors
[
0
]
,
word_vectors
[
1
]
)
(
f
"Similarity: {sim:.2f}"
)
Performance optimization tips
- Use
np.vectorizeReplace Python loops - Use
np.save/np.loadEfficiently store large matrices - Mastering the
np.einsumPerform complex tensor operations
Scikit-learn: Machine Learning Pipeline
NLP feature extraction
Example
from
sklearn.
feature_extraction
.
text
import
TfidfVectorizer
corpus
=
[
'This is the first document.'
,
'This document is the second document.'
,
'And this is the third one.'
]
Create a TF-IDF vectorizer
vectorizer
=
TfidfVectorizer
(
)
X
=
vectorizer.
fit_transform
(
corpus
)
(
f
"Feature matrix shape: {X.shape}"
)
(
f
"Feature names: {vectorizer.get_feature_names_out()}"
)
Complete NLP pipeline example
Example
from
sklearn.
pipeline
import
Pipeline
from
sklearn.
ensemble
import
RandomForestClassifier
from
sklearn.
model_selection
import
train_test_split
Create a pipeline
nlp_pipeline
=
Pipeline
(
[
(
'tfidf'
,
TfidfVectorizer
(
max_features
=
1000
)
)
,
(
'clf'
,
RandomForestClassifier
(
n_estimators
=
100
)
)
]
)
Sample data preparation
texts
=
[
"good movie"
,
"bad film"
,
"great story"
]
100
labels
=
[
1
,
0
,
1
]
100
Train-test split
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
texts
,
labels
)
Train the model
nlp_pipeline.
fit
(
X_train
,
y_train
)
Evaluation
(
f
"Test accuracy: {nlp_pipeline.score(X_test, y_test):.2f}"
)
Common NLP components
| Widget category | Main classes | Description |
|---|---|---|
| Feature extraction | CountVectorizer | Bag-of-words model |
| TfidfVectorizer | TF-IDF weighting | |
| Text preprocessing | HashingVectorizer | Memory-friendly feature extraction |
| Dimensionality reduction | TruncatedSVD | Latent semantic analysis |
Visualization Tools
Matplotlib basic visualization
Example
import
matplotlib.
pyplot
as
plt
Word frequency visualization example
words
=
[
'nlp'
,
'python'
,
'learning'
]
frequencies
=
[
25
,
40
,
35
]
plt.
figure
(
figsize
=
(
8
,
4
)
)
plt.
bar
(
words
,
frequencies
,
color
=
[
'#3498db'
,
'#2ecc71'
,
'#e74c3c'
]
)
plt.
title
(
'NLP Term Frequency Distribution'
)
plt.
xlabel
(
'Term'
)
plt.
ylabel
(
'Frequency'
)
plt.
show
(
)
Advanced visualization libraries
Seaborn: simpler statistical charts
Example
import
seaborn
as
sns
sns.
heatmap
(
tfidf_matrix
,
annot
=
True
)
WordCloud: generate word clouds
Example
from
wordcloud
import
WordCloud
wordcloud
=
WordCloud
(
)
.
generate
(
' '
.
join
(
texts
)
)
plt.
imshow
(
wordcloud
)
Plotly: interactive visualization
Example
import
plotly.
express
as
px
fig
=
px.
scatter_3d
(
embeddings
,
x
=
0
,
y
=
1
,
z
=
2
)
fig.
show
(
)
Comprehensive hands-on project
Complete workflow of sentiment analysis
Example
1. Data Loading
df
=
pd.
read_csv
(
'reviews.csv'
)
2. Data cleaning
df
[
'clean_text'
]
=
df
[
'text'
]
.
str
.
lower
(
)
.
str
.
replace
(
'[^\w\s]'
,
''
)
3. Feature engineering
vectorizer
=
TfidfVectorizer
(
max_features
=
5000
)
X
=
vectorizer.
fit_transform
(
df
[
'clean_text'
]
)
y
=
df
[
'sentiment'
]
4. Model training
from
sklearn.
svm
import
LinearSVC
model
=
LinearSVC
(
)
model.
fit
(
X
,
y
)
5. Visualization
import
seaborn
as
sns
from
sklearn.
metrics
import
confusion_matrix
y_pred
=
model.
predict
(
X
)
cm
=
confusion_matrix
(
y
,
y_pred
)
sns.
heatmap
(
cm
,
annot
=
True
,
fmt
=
'd'
)
Performance optimization tips
- Parallel processing: When using
n_jobsParameters - Feature selection:
SelectKBestReduce dimensionality - Pipeline caching:
memoryParameter for caching intermediate results
Recommended toolchain extensions
- NLTK: classic NLP toolkit
- spaCy: industrial-grade NLP processing
- Gensim: topic modeling and word vectors
- HuggingFace Transformers: pre-trained models

By mastering the combined use of these tools, you will be able to efficiently handle most NLP data processing tasks and lay a solid foundation for more advanced NLP applications.