dxmohammad-nlp-toolkit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dxmohammad_nlp_toolkit-0.1.0.dist-info/METADATA +358 -0
- dxmohammad_nlp_toolkit-0.1.0.dist-info/RECORD +19 -0
- dxmohammad_nlp_toolkit-0.1.0.dist-info/WHEEL +5 -0
- dxmohammad_nlp_toolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
- dxmohammad_nlp_toolkit-0.1.0.dist-info/top_level.txt +1 -0
- nlp_toolkit/__init__.py +0 -0
- nlp_toolkit/_nltk.py +24 -0
- nlp_toolkit/_spacy.py +14 -0
- nlp_toolkit/cleaning.py +50 -0
- nlp_toolkit/lemmatization.py +14 -0
- nlp_toolkit/ner.py +18 -0
- nlp_toolkit/nlp_pipeline.py +54 -0
- nlp_toolkit/normalization.py +29 -0
- nlp_toolkit/pos_tagging.py +15 -0
- nlp_toolkit/sentence_tokenization.py +14 -0
- nlp_toolkit/stemming.py +33 -0
- nlp_toolkit/stopwords.py +52 -0
- nlp_toolkit/tokenization.py +11 -0
- nlp_toolkit/vectorization.py +63 -0
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dxmohammad-nlp-toolkit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A modular Python toolkit for text preprocessing, linguistic analysis, and text vectorization.
|
|
5
|
+
Author: Mohammad
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/dxmohammad/nlp-toolkit
|
|
8
|
+
Project-URL: Repository, https://github.com/dxmohammad/nlp-toolkit
|
|
9
|
+
Project-URL: Issues, https://github.com/dxmohammad/nlp-toolkit/issues
|
|
10
|
+
Keywords: nlp,natural-language-processing,text-processing,tokenization,lemmatization,stemming,text-vectorization
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: nltk>=3.8
|
|
20
|
+
Requires-Dist: spacy>=3.7
|
|
21
|
+
Requires-Dist: scikit-learn>=1.2
|
|
22
|
+
Requires-Dist: scipy>=1.10
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# NLP Toolkit
|
|
26
|
+
|
|
27
|
+
A Python toolkit for Natural Language Processing (NLP), providing reusable functions for common text preprocessing, linguistic analysis, and text vectorization tasks.
|
|
28
|
+
|
|
29
|
+
The project is designed with a modular structure, allowing developers to use individual NLP functions or combine them into a complete text-processing pipeline.
|
|
30
|
+
|
|
31
|
+
## Features
|
|
32
|
+
|
|
33
|
+
The toolkit currently includes 11 modules:
|
|
34
|
+
|
|
35
|
+
| Module | Description |
|
|
36
|
+
|---|---|
|
|
37
|
+
| `cleaning` | Removes punctuation, numbers, and unnecessary characters |
|
|
38
|
+
| `normalization` | Normalizes text and whitespace |
|
|
39
|
+
| `tokenization` | Splits text into individual words |
|
|
40
|
+
| `stopwords` | Removes stopwords while preserving negation words |
|
|
41
|
+
| `stemming` | Applies Porter Stemming |
|
|
42
|
+
| `lemmatization` | Converts words into their base forms using spaCy |
|
|
43
|
+
| `pos_tagging` | Performs Part-of-Speech tagging |
|
|
44
|
+
| `ner` | Extracts Named Entities from text |
|
|
45
|
+
| `sentence_tokenization` | Splits text into sentences |
|
|
46
|
+
| `vectorization` | Supports Bag of Words and TF-IDF |
|
|
47
|
+
| `nlp_pipeline` | Combines multiple NLP operations into one pipeline |
|
|
48
|
+
|
|
49
|
+
## Project Structure
|
|
50
|
+
|
|
51
|
+
```text
|
|
52
|
+
nlp-toolkit/
|
|
53
|
+
│
|
|
54
|
+
├── nlp_toolkit/
|
|
55
|
+
│ ├── __init__.py
|
|
56
|
+
│ ├── _nltk.py
|
|
57
|
+
│ ├── _spacy.py
|
|
58
|
+
│ ├── cleaning.py
|
|
59
|
+
│ ├── normalization.py
|
|
60
|
+
│ ├── tokenization.py
|
|
61
|
+
│ ├── stopwords.py
|
|
62
|
+
│ ├── stemming.py
|
|
63
|
+
│ ├── lemmatization.py
|
|
64
|
+
│ ├── pos_tagging.py
|
|
65
|
+
│ ├── ner.py
|
|
66
|
+
│ ├── sentence_tokenization.py
|
|
67
|
+
│ ├── vectorization.py
|
|
68
|
+
│ └── nlp_pipeline.py
|
|
69
|
+
│
|
|
70
|
+
├── tests/
|
|
71
|
+
│ ├── test_cleaning.py
|
|
72
|
+
│ ├── test_lemmatization.py
|
|
73
|
+
│ ├── test_ner.py
|
|
74
|
+
│ ├── test_nlp_pipeline.py
|
|
75
|
+
│ ├── test_nltk_resources.py
|
|
76
|
+
│ ├── test_normalization.py
|
|
77
|
+
│ ├── test_pos_tagging.py
|
|
78
|
+
│ ├── test_sentence_tokenization.py
|
|
79
|
+
│ ├── test_stemming.py
|
|
80
|
+
│ ├── test_stopwords.py
|
|
81
|
+
│ ├── test_tokenization.py
|
|
82
|
+
│ └── test_vectorization.py
|
|
83
|
+
│
|
|
84
|
+
├── .gitignore
|
|
85
|
+
├── LICENSE
|
|
86
|
+
├── README.md
|
|
87
|
+
├── pyproject.toml
|
|
88
|
+
└── requirements.txt
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Requirements
|
|
92
|
+
|
|
93
|
+
- Python 3.10 or later.
|
|
94
|
+
- NLTK
|
|
95
|
+
- spaCy
|
|
96
|
+
- scikit-learn
|
|
97
|
+
- SciPy
|
|
98
|
+
|
|
99
|
+
## Installation
|
|
100
|
+
|
|
101
|
+
### 1. Clone the repository
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
git clone https://github.com/dxmohammad/nlp-toolkit.git
|
|
105
|
+
cd nlp-toolkit
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### 2. Install the package
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
pip install .
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
This installs the toolkit and its required Python dependencies.
|
|
115
|
+
|
|
116
|
+
### 3. Download the spaCy English model
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
python -m spacy download en_core_web_sm
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### 4. Download NLTK resources
|
|
123
|
+
|
|
124
|
+
Some modules require additional NLTK language resources.
|
|
125
|
+
|
|
126
|
+
Download the required resources using:
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
import nltk
|
|
130
|
+
|
|
131
|
+
nltk.download("punkt_tab")
|
|
132
|
+
nltk.download("stopwords")
|
|
133
|
+
nltk.download("averaged_perceptron_tagger_eng")
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
These resources are required by the relevant tokenization, stopword removal, and POS tagging modules.
|
|
137
|
+
|
|
138
|
+
## Usage
|
|
139
|
+
|
|
140
|
+
### 1. Text Cleaning
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from nlp_toolkit.cleaning import clean_text
|
|
144
|
+
|
|
145
|
+
text = "Hello, World! NLP is interesting."
|
|
146
|
+
result = clean_text(text)
|
|
147
|
+
|
|
148
|
+
print(result)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### 2. Text Normalization
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
from nlp_toolkit.normalization import normalize_text
|
|
155
|
+
|
|
156
|
+
text = " HELLO WORLD "
|
|
157
|
+
result = normalize_text(text)
|
|
158
|
+
|
|
159
|
+
print(result)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### 3. Word Tokenization
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
from nlp_toolkit.tokenization import tokenize_text
|
|
166
|
+
|
|
167
|
+
text = "I love Natural Language Processing."
|
|
168
|
+
tokens = tokenize_text(text)
|
|
169
|
+
|
|
170
|
+
print(tokens)
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### 4. Stopword Removal
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
from nlp_toolkit.stopwords import remove_stopwords
|
|
177
|
+
|
|
178
|
+
text = "This is an example of text processing."
|
|
179
|
+
result = remove_stopwords(text)
|
|
180
|
+
|
|
181
|
+
print(result)
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
### 5. Stemming
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
from nlp_toolkit.stemming import stem_words
|
|
188
|
+
|
|
189
|
+
words = ["playing", "studies", "running"]
|
|
190
|
+
result = stem_words(words)
|
|
191
|
+
|
|
192
|
+
print(result)
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### 6. Lemmatization
|
|
196
|
+
|
|
197
|
+
```python
|
|
198
|
+
from nlp_toolkit.lemmatization import lemmatize_text
|
|
199
|
+
|
|
200
|
+
text = "The children are playing."
|
|
201
|
+
result = lemmatize_text(text)
|
|
202
|
+
|
|
203
|
+
print(result)
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
### 7. Part-of-Speech Tagging
|
|
207
|
+
|
|
208
|
+
```python
|
|
209
|
+
from nlp_toolkit.pos_tagging import get_pos_tags
|
|
210
|
+
|
|
211
|
+
text = "The researchers develop intelligent systems."
|
|
212
|
+
result = get_pos_tags(text)
|
|
213
|
+
|
|
214
|
+
print(result)
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### 8. Named Entity Recognition
|
|
218
|
+
|
|
219
|
+
```python
|
|
220
|
+
from nlp_toolkit.ner import extract_entities
|
|
221
|
+
|
|
222
|
+
text = "Elon Musk founded SpaceX."
|
|
223
|
+
result = extract_entities(text)
|
|
224
|
+
|
|
225
|
+
print(result)
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
### 9. Sentence Tokenization
|
|
229
|
+
|
|
230
|
+
```python
|
|
231
|
+
from nlp_toolkit.sentence_tokenization import tokenize_sentences
|
|
232
|
+
|
|
233
|
+
text = "NLP is interesting. Python is useful."
|
|
234
|
+
result = tokenize_sentences(text)
|
|
235
|
+
|
|
236
|
+
print(result)
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
### 10. Text Vectorization
|
|
240
|
+
|
|
241
|
+
**Bag of Words**
|
|
242
|
+
|
|
243
|
+
```python
|
|
244
|
+
from nlp_toolkit.vectorization import bag_of_words
|
|
245
|
+
|
|
246
|
+
documents = [
|
|
247
|
+
"I love machine learning",
|
|
248
|
+
"Machine learning is interesting"
|
|
249
|
+
]
|
|
250
|
+
|
|
251
|
+
matrix, vocabulary = bag_of_words(documents)
|
|
252
|
+
|
|
253
|
+
print(matrix.toarray())
|
|
254
|
+
print(vocabulary)
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
**TF-IDF**
|
|
258
|
+
|
|
259
|
+
```python
|
|
260
|
+
from nlp_toolkit.vectorization import tfidf_vectorization
|
|
261
|
+
|
|
262
|
+
documents = [
|
|
263
|
+
"I love machine learning",
|
|
264
|
+
"Machine learning is interesting"
|
|
265
|
+
]
|
|
266
|
+
|
|
267
|
+
matrix, vocabulary = tfidf_vectorization(documents)
|
|
268
|
+
|
|
269
|
+
print(matrix.toarray())
|
|
270
|
+
print(vocabulary)
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
### 11. Complete NLP Pipeline
|
|
274
|
+
|
|
275
|
+
```python
|
|
276
|
+
from nlp_toolkit.nlp_pipeline import process_text
|
|
277
|
+
|
|
278
|
+
text = "Elon Musk is developing artificial intelligence."
|
|
279
|
+
|
|
280
|
+
result = process_text(text)
|
|
281
|
+
|
|
282
|
+
for key, value in result.items():
|
|
283
|
+
print(f"{key}: {value}")
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
## Testing
|
|
287
|
+
|
|
288
|
+
The project includes 12 individual test files.
|
|
289
|
+
|
|
290
|
+
To run all tests from the project root directory using PowerShell:
|
|
291
|
+
|
|
292
|
+
```powershell
|
|
293
|
+
$python = "python"
|
|
294
|
+
$env:PYTHONPATH = (Get-Location).Path
|
|
295
|
+
|
|
296
|
+
try {
|
|
297
|
+
$testFiles = Get-ChildItem .\tests -Filter "test_*.py" -File | Sort-Object Name
|
|
298
|
+
|
|
299
|
+
foreach ($test in $testFiles) {
|
|
300
|
+
Write-Host "Testing $($test.Name)"
|
|
301
|
+
|
|
302
|
+
& $python $test.FullName
|
|
303
|
+
|
|
304
|
+
if ($LASTEXITCODE -ne 0) {
|
|
305
|
+
throw "Test failed: $($test.Name)"
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
Write-Host "ALL PROJECT TESTS PASSED!"
|
|
310
|
+
}
|
|
311
|
+
finally {
|
|
312
|
+
Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue
|
|
313
|
+
}
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
## Technologies Used
|
|
317
|
+
|
|
318
|
+
- Python
|
|
319
|
+
- NLTK
|
|
320
|
+
- spaCy
|
|
321
|
+
- scikit-learn
|
|
322
|
+
- SciPy
|
|
323
|
+
|
|
324
|
+
## Project Status
|
|
325
|
+
|
|
326
|
+
The initial implementation of the toolkit is complete.
|
|
327
|
+
|
|
328
|
+
The project has been organized as an installable Python package, with:
|
|
329
|
+
|
|
330
|
+
- 11 functional NLP modules.
|
|
331
|
+
- 12 individual test files.
|
|
332
|
+
- Modular NLTK resource management.
|
|
333
|
+
- Cached spaCy model loading.
|
|
334
|
+
- Package configuration using `pyproject.toml`.
|
|
335
|
+
- Wheel and source distribution builds.
|
|
336
|
+
- Successful local installation testing in an independent Python environment.
|
|
337
|
+
|
|
338
|
+
The package has not yet been published on PyPI.
|
|
339
|
+
|
|
340
|
+
## Future Improvements
|
|
341
|
+
|
|
342
|
+
- Expand language support.
|
|
343
|
+
- Add more text preprocessing techniques.
|
|
344
|
+
- Improve pipeline flexibility.
|
|
345
|
+
- Expand automated test coverage.
|
|
346
|
+
- Publish the package on PyPI.
|
|
347
|
+
|
|
348
|
+
## License
|
|
349
|
+
|
|
350
|
+
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
|
351
|
+
|
|
352
|
+
## Author
|
|
353
|
+
|
|
354
|
+
**Mohammad**
|
|
355
|
+
|
|
356
|
+
GitHub: [@dxmohammad](https://github.com/dxmohammad)
|
|
357
|
+
|
|
358
|
+
Project Repository: [nlp-toolkit](https://github.com/dxmohammad/nlp-toolkit)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
dxmohammad_nlp_toolkit-0.1.0.dist-info/licenses/LICENSE,sha256=P9qUb0WuhPztKe946_bnjrD0l2wsei2VIWS_WhFjDTg,1086
|
|
2
|
+
nlp_toolkit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
nlp_toolkit/_nltk.py,sha256=ir3XA-TFYtTcXYNsy5nD0aaJEyiJz6bAS2aOqOqUnL4,707
|
|
4
|
+
nlp_toolkit/_spacy.py,sha256=EtMKFUosE7n_eMLQGp8vQtnomb_O2ZJjBY1ABewXUbM,362
|
|
5
|
+
nlp_toolkit/cleaning.py,sha256=Tmcbs4flz4ZjPqjMw1UoYR1vPPretIpHAki0qjOzd3I,1267
|
|
6
|
+
nlp_toolkit/lemmatization.py,sha256=oErxA_aHc83n0Oor_9nYsoH8FLq1tflSw20sf6lfgw8,317
|
|
7
|
+
nlp_toolkit/ner.py,sha256=I-vaEpDo8uICUOBgnJoizFWSwr6v2Dsqlt9-FiJWopM,424
|
|
8
|
+
nlp_toolkit/nlp_pipeline.py,sha256=FnRk63F3vebPO_K206LTNSa0OC6MiUzBZ8xTuVksuAU,1495
|
|
9
|
+
nlp_toolkit/normalization.py,sha256=GnrSwRt7ccEkHlsk3c389C64PiAbV0KTijAo9jTRULc,586
|
|
10
|
+
nlp_toolkit/pos_tagging.py,sha256=CwMmfqX56tEBg_dra8fULq8KxYDoAKqohWB5NM9oh28,419
|
|
11
|
+
nlp_toolkit/sentence_tokenization.py,sha256=fvz26v7PQU1XJkyAaNXJTVf-Ne6ThmQ1X_-nc7nYzzQ,342
|
|
12
|
+
nlp_toolkit/stemming.py,sha256=VANJWe1qiCiRBO4FN9IcNd-DXp6Fci3UqlHTsFjRD2A,688
|
|
13
|
+
nlp_toolkit/stopwords.py,sha256=Ba_pKxNMbzFK2GCNhCoHaMpTQpkhHSemc2EJZOrV79Q,1309
|
|
14
|
+
nlp_toolkit/tokenization.py,sha256=4wQxDupP97qSDdA4Ti7c_n9s7Pm72AATJNWX9eKFUdE,290
|
|
15
|
+
nlp_toolkit/vectorization.py,sha256=ifNvmj9HrdlRZhs6C6AeOUkoKrCSYbLpmZX3Tg3pv-E,1618
|
|
16
|
+
dxmohammad_nlp_toolkit-0.1.0.dist-info/METADATA,sha256=dFxkvJqilg4gYr0EQxc5g2aJ9DIz5Qya1dDPF176wLE,8349
|
|
17
|
+
dxmohammad_nlp_toolkit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
18
|
+
dxmohammad_nlp_toolkit-0.1.0.dist-info/top_level.txt,sha256=A0QQaPbZ8J9lUY0ubL1r2_B7a9Km2CAbOtXc-xz4DSk,12
|
|
19
|
+
dxmohammad_nlp_toolkit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dxmohammad
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
nlp_toolkit
|
nlp_toolkit/__init__.py
ADDED
|
File without changes
|
nlp_toolkit/_nltk.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import nltk
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
_NLTK_RESOURCES = {
|
|
5
|
+
"punkt_tab": "tokenizers/punkt_tab/english/",
|
|
6
|
+
"stopwords": "corpora/stopwords",
|
|
7
|
+
"averaged_perceptron_tagger_eng": (
|
|
8
|
+
"taggers/averaged_perceptron_tagger_eng/"
|
|
9
|
+
),
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def ensure_nltk_resource(resource: str) -> None:
|
|
14
|
+
if resource not in _NLTK_RESOURCES:
|
|
15
|
+
raise ValueError(f"Unknown NLTK resource: {resource}")
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
nltk.data.find(_NLTK_RESOURCES[resource])
|
|
19
|
+
except LookupError as error:
|
|
20
|
+
raise LookupError(
|
|
21
|
+
f"Required NLTK resource '{resource}' is missing. "
|
|
22
|
+
f"Download it using: "
|
|
23
|
+
f"python -c \"import nltk; nltk.download('{resource}')\""
|
|
24
|
+
) from error
|
nlp_toolkit/_spacy.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from functools import lru_cache
|
|
2
|
+
import spacy
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@lru_cache(maxsize=1)
|
|
6
|
+
def get_nlp():
|
|
7
|
+
try:
|
|
8
|
+
return spacy.load("en_core_web_sm")
|
|
9
|
+
except OSError as error:
|
|
10
|
+
raise OSError(
|
|
11
|
+
"spaCy English model is not installed. "
|
|
12
|
+
"Install it using: "
|
|
13
|
+
"python -m spacy download en_core_web_sm"
|
|
14
|
+
) from error
|
nlp_toolkit/cleaning.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def clean_text(
|
|
6
|
+
text: str,
|
|
7
|
+
remove_punctuation: bool = True,
|
|
8
|
+
remove_numbers: bool = False,
|
|
9
|
+
remove_extra_spaces: bool = True
|
|
10
|
+
) -> str:
|
|
11
|
+
"""
|
|
12
|
+
Clean text by optionally removing punctuation and numbers,
|
|
13
|
+
and normalizing whitespace.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
text: Input text.
|
|
17
|
+
remove_punctuation: Replace punctuation with spaces.
|
|
18
|
+
remove_numbers: Remove numeric characters.
|
|
19
|
+
remove_extra_spaces: Collapse repeated whitespace.
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
Cleaned text.
|
|
23
|
+
|
|
24
|
+
Raises:
|
|
25
|
+
TypeError: If text or any option has an invalid type.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
if not isinstance(text, str):
|
|
29
|
+
raise TypeError("Input must be a string.")
|
|
30
|
+
|
|
31
|
+
options = {
|
|
32
|
+
"remove_punctuation": remove_punctuation,
|
|
33
|
+
"remove_numbers": remove_numbers,
|
|
34
|
+
"remove_extra_spaces": remove_extra_spaces
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
for name, value in options.items():
|
|
38
|
+
if not isinstance(value, bool):
|
|
39
|
+
raise TypeError(f"{name} must be a boolean.")
|
|
40
|
+
|
|
41
|
+
if remove_punctuation:
|
|
42
|
+
text = re.sub(r"[^\w\s]|_", " ", text)
|
|
43
|
+
|
|
44
|
+
if remove_numbers:
|
|
45
|
+
text = re.sub(r"\d+", "", text)
|
|
46
|
+
|
|
47
|
+
if remove_extra_spaces:
|
|
48
|
+
text = re.sub(r"\s+", " ", text).strip()
|
|
49
|
+
|
|
50
|
+
return text
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from ._spacy import get_nlp
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def lemmatize_text(text: str) -> list[str]:
|
|
5
|
+
if not isinstance(text, str):
|
|
6
|
+
raise TypeError("Input must be a string.")
|
|
7
|
+
|
|
8
|
+
doc = get_nlp()(text)
|
|
9
|
+
|
|
10
|
+
return [
|
|
11
|
+
token.lemma_
|
|
12
|
+
for token in doc
|
|
13
|
+
if not token.is_punct and not token.is_space
|
|
14
|
+
]
|
nlp_toolkit/ner.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import spacy
|
|
2
|
+
from ._spacy import get_nlp
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def extract_entities(text: str) -> list[dict[str, str]]:
|
|
6
|
+
if not isinstance(text, str):
|
|
7
|
+
raise TypeError("Input must be a string.")
|
|
8
|
+
|
|
9
|
+
doc = get_nlp()(text)
|
|
10
|
+
|
|
11
|
+
return [
|
|
12
|
+
{
|
|
13
|
+
"text": entity.text,
|
|
14
|
+
"label": entity.label_,
|
|
15
|
+
"description": spacy.explain(entity.label_)
|
|
16
|
+
}
|
|
17
|
+
for entity in doc.ents
|
|
18
|
+
]
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
|
|
2
|
+
from .cleaning import clean_text
|
|
3
|
+
from .normalization import normalize_text
|
|
4
|
+
from .tokenization import tokenize_text
|
|
5
|
+
from .stopwords import remove_stopwords
|
|
6
|
+
from .stemming import stem_words
|
|
7
|
+
from .lemmatization import lemmatize_text
|
|
8
|
+
from .pos_tagging import get_pos_tags
|
|
9
|
+
from .ner import extract_entities
|
|
10
|
+
from .sentence_tokenization import tokenize_sentences
|
|
11
|
+
|
|
12
|
+
def process_text(text: str) -> dict:
|
|
13
|
+
"""
|
|
14
|
+
Process text using the NLP Toolkit modules.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
if not isinstance(text, str):
|
|
18
|
+
raise TypeError("Input must be a string.")
|
|
19
|
+
|
|
20
|
+
if not text.strip():
|
|
21
|
+
raise ValueError("Input text cannot be empty.")
|
|
22
|
+
|
|
23
|
+
# Text preprocessing
|
|
24
|
+
cleaned_text = clean_text(text)
|
|
25
|
+
|
|
26
|
+
normalized_text = normalize_text(cleaned_text)
|
|
27
|
+
|
|
28
|
+
# Token processing
|
|
29
|
+
tokens = tokenize_text(normalized_text)
|
|
30
|
+
|
|
31
|
+
filtered_tokens = remove_stopwords(normalized_text)
|
|
32
|
+
|
|
33
|
+
stemmed_tokens = stem_words(filtered_tokens)
|
|
34
|
+
|
|
35
|
+
# Linguistic analysis on original text
|
|
36
|
+
sentences = tokenize_sentences(text)
|
|
37
|
+
|
|
38
|
+
lemmas = lemmatize_text(text)
|
|
39
|
+
|
|
40
|
+
pos_tags = get_pos_tags(text)
|
|
41
|
+
|
|
42
|
+
entities = extract_entities(text)
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
"cleaned_text": cleaned_text,
|
|
46
|
+
"normalized_text": normalized_text,
|
|
47
|
+
"tokens": tokens,
|
|
48
|
+
"filtered_tokens": filtered_tokens,
|
|
49
|
+
"stemmed_tokens": stemmed_tokens,
|
|
50
|
+
"sentences": sentences,
|
|
51
|
+
"lemmas": lemmas,
|
|
52
|
+
"pos_tags": pos_tags,
|
|
53
|
+
"entities": entities
|
|
54
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
|
|
2
|
+
import unicodedata
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def normalize_text(text: str) -> str:
|
|
6
|
+
"""
|
|
7
|
+
Normalize text using Unicode normalization,
|
|
8
|
+
lowercase conversion, and whitespace cleanup.
|
|
9
|
+
|
|
10
|
+
Args:
|
|
11
|
+
text: Input text.
|
|
12
|
+
|
|
13
|
+
Returns:
|
|
14
|
+
Normalized text.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
if not isinstance(text, str):
|
|
18
|
+
raise TypeError("Input must be a string.")
|
|
19
|
+
|
|
20
|
+
# Apply Unicode normalization
|
|
21
|
+
text = unicodedata.normalize("NFKC", text)
|
|
22
|
+
|
|
23
|
+
# Convert text to lowercase
|
|
24
|
+
text = text.lower()
|
|
25
|
+
|
|
26
|
+
# Remove extra whitespace
|
|
27
|
+
text = " ".join(text.split())
|
|
28
|
+
|
|
29
|
+
return text
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from nltk import pos_tag
|
|
2
|
+
from nltk.tokenize import word_tokenize
|
|
3
|
+
from ._nltk import ensure_nltk_resource
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def get_pos_tags(text: str) -> list[tuple[str, str]]:
|
|
7
|
+
if not isinstance(text, str):
|
|
8
|
+
raise TypeError("Input must be a string.")
|
|
9
|
+
|
|
10
|
+
ensure_nltk_resource("punkt_tab")
|
|
11
|
+
ensure_nltk_resource("averaged_perceptron_tagger_eng")
|
|
12
|
+
|
|
13
|
+
tokens = word_tokenize(text)
|
|
14
|
+
|
|
15
|
+
return pos_tag(tokens)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from nltk.tokenize import sent_tokenize
|
|
2
|
+
from ._nltk import ensure_nltk_resource
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def tokenize_sentences(text: str) -> list[str]:
|
|
6
|
+
if not isinstance(text, str):
|
|
7
|
+
raise TypeError("Input must be a string.")
|
|
8
|
+
|
|
9
|
+
if not text.strip():
|
|
10
|
+
return []
|
|
11
|
+
|
|
12
|
+
ensure_nltk_resource("punkt_tab")
|
|
13
|
+
|
|
14
|
+
return sent_tokenize(text)
|
nlp_toolkit/stemming.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
|
|
2
|
+
from nltk.stem import PorterStemmer
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
_stemmer = PorterStemmer()
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def stem_words(words: list[str]) -> list[str]:
|
|
9
|
+
"""
|
|
10
|
+
Apply Porter Stemming to a list of English words.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
words: A list of input words.
|
|
14
|
+
|
|
15
|
+
Returns:
|
|
16
|
+
A list of stemmed words.
|
|
17
|
+
|
|
18
|
+
Raises:
|
|
19
|
+
TypeError: If input is not a list of strings.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
if not isinstance(words, list):
|
|
23
|
+
raise TypeError("Input must be a list.")
|
|
24
|
+
|
|
25
|
+
if not all(isinstance(word, str) for word in words):
|
|
26
|
+
raise TypeError("All items must be strings.")
|
|
27
|
+
|
|
28
|
+
stemmed_words = [
|
|
29
|
+
_stemmer.stem(word)
|
|
30
|
+
for word in words
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
return stemmed_words
|
nlp_toolkit/stopwords.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from ._nltk import ensure_nltk_resource
|
|
2
|
+
from nltk.corpus import stopwords
|
|
3
|
+
from nltk.tokenize import word_tokenize
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def remove_stopwords(
|
|
7
|
+
text: str,
|
|
8
|
+
language: str = "english"
|
|
9
|
+
) -> list[str]:
|
|
10
|
+
"""
|
|
11
|
+
Remove common stopwords from text while preserving negation.
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
text: Input text.
|
|
15
|
+
language: Stopwords language.
|
|
16
|
+
|
|
17
|
+
Returns:
|
|
18
|
+
A list of filtered tokens.
|
|
19
|
+
|
|
20
|
+
Raises:
|
|
21
|
+
TypeError: If input types are invalid.
|
|
22
|
+
LookupError: If required NLTK resources are unavailable.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
if not isinstance(text, str):
|
|
26
|
+
raise TypeError("Input must be a string.")
|
|
27
|
+
|
|
28
|
+
if not isinstance(language, str):
|
|
29
|
+
raise TypeError("Language must be a string.")
|
|
30
|
+
|
|
31
|
+
ensure_nltk_resource("stopwords")
|
|
32
|
+
ensure_nltk_resource("punkt_tab")
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
stop_words = set(stopwords.words(language))
|
|
36
|
+
except (LookupError, OSError) as error:
|
|
37
|
+
raise LookupError(
|
|
38
|
+
f"Stopwords data for '{language}' is unavailable."
|
|
39
|
+
) from error
|
|
40
|
+
|
|
41
|
+
# Preserve negation words
|
|
42
|
+
stop_words.discard("not")
|
|
43
|
+
stop_words.discard("no")
|
|
44
|
+
|
|
45
|
+
tokens = word_tokenize(text)
|
|
46
|
+
|
|
47
|
+
filtered_tokens = [
|
|
48
|
+
word for word in tokens
|
|
49
|
+
if word.lower() not in stop_words
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
return filtered_tokens
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from nltk.tokenize import word_tokenize
|
|
2
|
+
from ._nltk import ensure_nltk_resource
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def tokenize_text(text: str) -> list[str]:
|
|
6
|
+
if not isinstance(text, str):
|
|
7
|
+
raise TypeError("Input must be a string.")
|
|
8
|
+
|
|
9
|
+
ensure_nltk_resource("punkt_tab")
|
|
10
|
+
|
|
11
|
+
return word_tokenize(text)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
|
|
2
|
+
from scipy.sparse import csr_matrix
|
|
3
|
+
from sklearn.feature_extraction.text import (
|
|
4
|
+
CountVectorizer,
|
|
5
|
+
TfidfVectorizer
|
|
6
|
+
)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _validate_documents(documents: list[str]) -> None:
|
|
10
|
+
"""Validate input documents."""
|
|
11
|
+
|
|
12
|
+
if not isinstance(documents, list):
|
|
13
|
+
raise TypeError("Input must be a list.")
|
|
14
|
+
|
|
15
|
+
if not all(isinstance(doc, str) for doc in documents):
|
|
16
|
+
raise TypeError("All documents must be strings.")
|
|
17
|
+
|
|
18
|
+
if not documents or not any(doc.strip() for doc in documents):
|
|
19
|
+
raise ValueError("Documents cannot be empty.")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _vectorize_documents(
|
|
23
|
+
documents: list[str],
|
|
24
|
+
vectorizer: CountVectorizer | TfidfVectorizer
|
|
25
|
+
) -> tuple[csr_matrix, list[str]]:
|
|
26
|
+
"""Convert documents into numerical vectors."""
|
|
27
|
+
|
|
28
|
+
_validate_documents(documents)
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
matrix = vectorizer.fit_transform(documents)
|
|
32
|
+
except ValueError as error:
|
|
33
|
+
raise ValueError(
|
|
34
|
+
"No valid vocabulary found in the documents."
|
|
35
|
+
) from error
|
|
36
|
+
|
|
37
|
+
vocabulary = vectorizer.get_feature_names_out().tolist()
|
|
38
|
+
|
|
39
|
+
return matrix, vocabulary
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def bag_of_words(
|
|
43
|
+
documents: list[str]
|
|
44
|
+
) -> tuple[csr_matrix, list[str]]:
|
|
45
|
+
"""
|
|
46
|
+
Convert text documents into Bag of Words vectors.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
vectorizer = CountVectorizer()
|
|
50
|
+
|
|
51
|
+
return _vectorize_documents(documents, vectorizer)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def tfidf_vectorization(
|
|
55
|
+
documents: list[str]
|
|
56
|
+
) -> tuple[csr_matrix, list[str]]:
|
|
57
|
+
"""
|
|
58
|
+
Convert text documents into TF-IDF vectors.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
vectorizer = TfidfVectorizer()
|
|
62
|
+
|
|
63
|
+
return _vectorize_documents(documents, vectorizer)
|