Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions spacy/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
# Natural Language Processing With spaCy in Python

Corresponding code for the Real Python tutorial [Natural Language Processing With spaCy in Python](https://realpython.com/natural-language-processing-spacy-python/)
Corresponding code for the Real Python tutorial [Natural Language Processing With spaCy in Python](https://realpython.com/natural-language-processing-spacy-python/).

All the examples from the tutorial have been combined into one file. For the best experience, use VS Code with the [Jupyter extension](https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter). This uses the `# %%` token as a delimiter for separate cells, allowing you to run cells one by one and inspect the output.
## Setup

You need Python 3.12 or later. Create and activate a virtual environment, then install the pinned dependencies, which include the `en_core_web_sm` English model:

```sh
$ python -m venv venv
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txt
```

## Usage

All the examples from the tutorial have been combined into one file, `examples.py`. For the best experience, use VS Code with the [Jupyter extension](https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter). This uses the `# %%` token as a delimiter for separate cells, allowing you to run cells one by one and inspect the output.

Run the cells from the `spacy/` folder so that `examples.py` finds `introduction.txt`. The `displacy.serve()` cells start a local web server at `http://127.0.0.1:5000` and block until you stop it with <kbd>Ctrl</kbd>+<kbd>C</kbd>.
47 changes: 26 additions & 21 deletions spacy/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,18 @@
# %% Reading text from a file instead

file_name = "introduction.txt"
introduction_file_text = pathlib.Path(file_name).read_text()
introduction_file_text = pathlib.Path(file_name).read_text(encoding="utf-8")
introduction_file_doc = nlp(introduction_file_text)

# %% Extracting tokens and reading on one line

# Extract tokens for the given doc
print([token.text for token in nlp(pathlib.Path(file_name).read_text())])
print(
[
token.text
for token in nlp(pathlib.Path(file_name).read_text(encoding="utf-8"))
]
)

# %% Extracting sentences

Expand All @@ -55,7 +60,7 @@

@Language.component("set_custom_boundaries")
def set_custom_boundaries(doc):
"""Adds support to use `...` as the delimiter for sentence detection"""
"""Add support to use `...` as a delimiter for sentence detection"""
for token in doc[:-1]:
if token.text == "...":
doc[token.i + 1].is_sent_start = True
Expand Down Expand Up @@ -107,7 +112,7 @@ def set_custom_boundaries(doc):

custom_about_text = (
"Gus Proto is a Python developer currently"
" working for a London@based London-based Fintech"
" working for a London@based Fintech"
" company. He is interested in learning"
" Natural Language Processing."
)
Expand Down Expand Up @@ -220,26 +225,25 @@ def set_custom_boundaries(doc):

# %% Part-of-speech tagging

for token in about_doc[:5]:
for token in about_doc:
print(
f"""
TOKEN: {str(token)}
=====
TAG: {str(token.tag_):10} POS: {token.pos_}
EXPLANATION: {spacy.explain(token.tag_)}"""
TOKEN: {str(token)}
=====
TAG: {str(token.tag_):10} POS: {token.pos_}
EXPLANATION: {spacy.explain(token.tag_)}"""
)

# %% Categorizing words based on their POS

nouns = []
adjectives = []
for token in about_doc:
if token.pos_ == "NOUN":
nouns.append(token)
if token.pos_ == "ADJ":
adjectives.append(token)

elif token.pos_ == "NOUN":
nouns.append(token)

print(f"{nouns = }")

print(f"{adjectives = }")
Expand Down Expand Up @@ -294,18 +298,17 @@ def preprocess_token(token):

def extract_full_name(nlp_doc):
pattern = [{"POS": "PROPN"}, {"POS": "PROPN"}]
matcher.add("FULL_NAME", patterns=[pattern])
matcher.add("FULL_NAME", [pattern])
matches = matcher(nlp_doc)
for _, start, end in matches:
span = nlp_doc[start:end]
return span.text
yield span.text


print(extract_full_name(about_doc))
print(next(extract_full_name(about_doc)))

# %% Extracting phone numbers from text with patterns

matcher = Matcher(nlp.vocab)
conference_org_text = (
"There is a developer conference"
" happening on 21 July 2019 in London. It is titled"
Expand All @@ -322,9 +325,10 @@ def extract_phone_number(nlp_doc):
{"ORTH": ")"},
{"SHAPE": "ddd"},
{"ORTH": "-", "OP": "?"},
{"SHAPE": "ddd"},
{"SHAPE": "dddd"},
]
matcher.add("PHONE_NUMBER", patterns=[pattern])
matcher = Matcher(nlp.vocab)
matcher.add("PHONE_NUMBER", [pattern])
matches = matcher(nlp_doc)
for _, start, end in matches:
span = nlp_doc[start:end]
Expand Down Expand Up @@ -399,8 +403,9 @@ def flatten_tree(tree):
# %% Verb phrase detection

about_talk_text = (
"In this talk, the speaker will introduce the audience to the use"
" cases of Natural Language Processing in Fintech, making use of"
"The talk will introduce reader about use"
" cases of Natural Language Processing in"
" Fintech, making use of"
" interesting examples along the way."
)

Expand Down Expand Up @@ -434,7 +439,7 @@ def flatten_tree(tree):
{ent.start_char = }
{ent.end_char = }
{ent.label_ = }
{spacy.explain(ent.label_) = }"""
spacy.explain('{ent.label_}') = {spacy.explain(ent.label_)}"""
)

displacy.serve(piano_class_doc, style="ent")
Expand Down
2 changes: 1 addition & 1 deletion spacy/introduction.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
This tutorial is about Natural Language Processing in Spacy.
This tutorial is about Natural Language Processing in spaCy.
98 changes: 57 additions & 41 deletions spacy/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,42 +1,58 @@
blis==0.7.9
cachetools==5.2.0
catalogue==2.0.8
certifi==2022.12.7
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.6
confection==0.0.3
cymem==2.0.7
cytoolz==0.12.0
en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.1/en_core_web_sm-3.4.1-py3-none-any.whl
idna==3.4
jellyfish==0.9.0
Jinja2==3.1.2
joblib==1.2.0
langcodes==3.3.0
MarkupSafe==2.1.1
murmurhash==1.0.9
networkx==2.8.8
numpy==1.24.0
packaging==22.0
pathy==0.10.1
preshed==3.0.8
pydantic==1.10.2
pyphen==0.13.2
requests==2.28.1
scikit-learn==1.2.0
scipy==1.9.3
smart-open==6.3.0
spacy==3.4.4
spacy-legacy==3.0.10
spacy-loggers==1.0.4
srsly==2.4.5
annotated-doc==0.0.7
annotated-types==0.8.0
anyio==4.16.0
blis==1.3.4
cachetools==8.0.4
catalogue==2.0.10
certifi==2026.11.20
charset-normalizer==3.5.3
click==8.5.1
cloudpathlib==0.26.0
cloudpickle==3.1.3
confection==1.3.4
cymem==2.0.16
cytoolz==1.2.0
en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl
h11==0.16.0
httpcore==1.0.9
httpx==0.29.0
idna==3.20
jellyfish==1.3.0
jinja2==3.1.6
joblib==1.6.0
markdown-it-py==4.3.0
markupsafe==3.0.4
mdurl==0.1.2
murmurhash==1.0.16
narwhals==2.30.0
networkx==3.7
numpy==2.5.5
packaging==26.4
preshed==3.0.15
pydantic==2.14.4
pydantic-core==2.50.5
pygments==2.21.0
pyphen==0.19.0
requests==2.34.2
rich==15.0.0
scikit-learn==1.9.1
scipy==1.18.1
setuptools==84.2.1
shellingham==1.5.4
smart-open==10.0.1
spacy==3.8.18
spacy-legacy==3.0.12
spacy-loggers==1.0.5
srsly==2.5.6
textacy==0.12.0
thinc==8.1.5
threadpoolctl==3.1.0
toolz==0.12.0
tqdm==4.64.1
typer==0.7.0
typing_extensions==4.4.0
urllib3==1.26.13
wasabi==0.10.1
thinc==8.3.14
threadpoolctl==3.8.0
toolz==1.2.0
tqdm==4.70.1
typer==0.29.3
typing-extensions==4.16.0
typing-inspection==0.4.5
urllib3==2.8.0
wasabi==1.1.3
weasel==1.0.1
wrapt==2.5.2
Loading