Learn how to split strings into smaller units called tokens using various techniques in Python. Master concepts like splitting, regex, and advanced tokenization methods with practical examples and exercises.
Step 1: Understanding String Tokenization
String tokenization is the process of breaking a string into smaller units called tokens. Tokens can be words, numbers, punctuation marks, or other meaningful elements, depending on the application's requirements.
Why tokenize?
- Text preprocessing for Natural Language Processing tasks
- Parsing and analyzing log files
- Data cleaning and preparation
- Information extraction from unstructured text
Practice Exercise
Show Solution
Step 2: Basic String Splitting
Python's str.split() method is the simplest way to tokenize a string. It splits the string by a specified delimiter (whitespace by default) and returns a list of tokens.
sentence = "The quick brown fox jumps over the lazy dog."
tokens = sentence.split()
print(tokens) # Output: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
You can specify a custom delimiter:
csv_data = "John,Doe,35,Engineer"
tokens = csv_data.split(',')
print(tokens) # Output: ['John', 'Doe', '35', 'Engineer']sentence = "The quick brown fox jumps over the lazy dog."
tokens = sentence.split()
print(tokens)Practice Exercise
Write a Python function that takes a file path as input, reads the file's contents, and tokenizes the text using str.split(). The function should return a list of tokens.
Show Solution
```python
def tokenize_file(file_path):
"""Reads a file and tokenizes its contents."""
try:
with open(file_path, 'r') as file:
text = file.read()
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return []
tokens = text.split()
return tokens
# Example usage
file_path = 'example.txt'
tokens = tokenize_file(file_path)
print(tokens)
```
Explanation:
- The `tokenize_file` function takes a `file_path` as input.
- It opens the file using `with` statement and reads its contents into the `text` variable.
- If the file is not found, it prints an error message and returns an empty list.
- The `text` is tokenized using `str.split()`, which splits the string by whitespace characters.
- The resulting list of tokens is returned.Step 3: Splitting with Regular Expressions
Regular expressions (regex) provide a more powerful way to tokenize strings based on complex patterns. Python's re module offers functions like re.split() and re.findall() for tokenization.
import re
text = "Hello, 123! This... is@sample.com"
# Split by one or more non-word characters
tokens = re.split(r'\W+', text)
print(tokens) # Output: ['Hello', '123', 'This', 'is', 'sample', 'com']
# Find all word tokens
tokens = re.findall(r'\w+', text)
print(tokens) # Output: ['Hello', '123', 'This', 'is', 'sample', 'com']
Regular expressions allow you to define complex patterns for tokenization, making them more flexible than simple delimiters.
import re
text = "Hello, 123! This... is@sample.com"
tokens = re.split(r'\W+', text)
print(tokens)Practice Exercise
Write a Python function that takes a string as input and tokenizes it using regular expressions. The function should split the string by any non-word characters (digits, punctuation, whitespace) and return a list of tokens containing only word characters.
Show Solution
```python
import re
def tokenize_string(text):
"""Tokenizes a string using regex, splitting by non-word characters."""
pattern = r'\W+' # Match one or more non-word characters
tokens = re.split(pattern, text)
# Filter out empty strings
tokens = [token for token in tokens if token]
return tokens
# Example usage
text = "Hello, 123! This... is@sample.com"
tokens = tokenize_string(text)
print(tokens) # Output: ['Hello', '123', 'This', 'is', 'sample', 'com']
```
Explanation:
- The `tokenize_string` function takes a `text` string as input.
- The regular expression pattern `r'\W+'` matches one or more non-word characters (digits, punctuation, whitespace).
- `re.split(pattern, text)` splits the string by the matched non-word characters.
- The resulting list of tokens may contain empty strings, so we filter them out using a list comprehension: `[token for token in tokens if token]`.
- The final list of tokens containing only word characters is returned.Step 4: Tokenizing with NLTK
The Natural Language Toolkit (NLTK) is a popular library for natural language processing tasks in Python. It provides various tokenizers for different types of text data.
Word Tokenizer
from nltk.tokenize import word_tokenize
text = "Don't worry, be happy!"
tokens = word_tokenize(text)
print(tokens) # Output: ['Do', "n't", 'worry', ',', 'be', 'happy', '!']
Sentence Tokenizer
from nltk.tokenize import sent_tokenize
text = "Hi there. How are you? I'm doing great."
sentences = sent_tokenize(text)
print(sentences) # Output: ['Hi there.', 'How are you?', 'I'm doing great.']
NLTK offers more advanced tokenizers like TreebankWordTokenizer, TweetTokenizer, and MWETokenizer for specific use cases.
from nltk.tokenize import word_tokenize
text = "Don't worry, be happy!"
tokens = word_tokenize(text)
print(tokens)Practice Exercise
Write a Python function that takes a text file path and a tokenizer function as input. The function should read the file's contents, tokenize the text using the provided tokenizer, and return a list of tokens. Test your function with both NLTK's word_tokenize and sent_tokenize functions.
Show Solution
```python
from nltk.tokenize import word_tokenize, sent_tokenize
def tokenize_file(file_path, tokenizer):
"""Tokenizes the contents of a file using the provided tokenizer function."""
try:
with open(file_path, 'r') as file:
text = file.read()
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return []
tokens = tokenizer(text)
return tokens
# Example usage with word_tokenize
file_path = 'example.txt'
tokens = tokenize_file(file_path, word_tokenize)
print("Word tokens:", tokens)
# Example usage with sent_tokenize
file_path = 'example.txt'
tokens = tokenize_file(file_path, sent_tokenize)
print("Sentence tokens:", tokens)
```
Explanation:
- The `tokenize_file` function takes a `file_path` and a `tokenizer` function as input.
- It opens the file using `with` statement and reads its contents into the `text` variable.
- If the file is not found, it prints an error message and returns an empty list.
- The `text` is tokenized using the provided `tokenizer` function.
- The resulting list of tokens is returned.
- In the example usage, the function is called with both `word_tokenize` and `sent_tokenize` from NLTK to demonstrate tokenization at word and sentence levels, respectively.Step 5: Tokenizing with Spacy
spaCy is another powerful library for natural language processing in Python. It provides a more advanced tokenizer that handles various linguistic phenomena and can be customized for specific use cases.
import spacy
# Load the English language model
nlp = spacy.load('en_core_web_sm')
text = "This is a sample sentence with some punctuation!"
doc = nlp(text)
# Access tokens
tokens = [token.text for token in doc]
print(tokens) # Output: ['This', 'is', 'a', 'sample', 'sentence', 'with', 'some', 'punctuation', '!']
# Access token attributes
for token in doc:
print(token.text, token.lemma_, token.pos_, token.dep_)
spaCy's tokenizer is more advanced than basic methods and can handle various edge cases. It also provides additional features like part-of-speech tagging, named entity recognition, and dependency parsing.
import spacy
nlp = spacy.load('en_core_web_sm')
text = "This is a sample sentence with some punctuation!"
doc = nlp(text)
tokens = [token.text for token in doc]
print(tokens)Practice Exercise
Write a Python function that takes a text string as input, tokenizes it using spaCy, and returns a list of tuples containing the token text and its part-of-speech tag.
Show Solution
```python
import spacy
def tokenize_with_pos(text):
"""Tokenizes text using spaCy and returns tokens with part-of-speech tags."""
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
tokens_with_pos = [(token.text, token.pos_) for token in doc]
return tokens_with_pos
# Example usage
text = "The quick brown fox jumps over the lazy dog."
tokens_and_pos = tokenize_with_pos(text)
print(tokens_and_pos)
# Output: [('The', 'DET'), ('quick', 'ADJ'), ('brown', 'ADJ'), ('fox', 'NOUN'), ('jumps', 'VERB'), ('over', 'ADP'), ('the', 'DET'), ('lazy', 'ADJ'), ('dog', 'NOUN'), ('.', 'PUNCT')]
```
Explanation:
- The `tokenize_with_pos` function takes a `text` string as input.
- It loads the English language model using `spacy.load('en_core_web_sm')`.
- The `text` is tokenized and processed using `nlp(text)`, which creates a `doc` object containing the tokens and their linguistic annotations.
- A list comprehension `[(token.text, token.pos_) for token in doc]` is used to create a list of tuples, where each tuple contains the token text and its part-of-speech tag (`token.pos_`).
- The resulting list of tuples is returned.
- In the example usage, the function is called with a sample text, and the output shows the tokens along with their part-of-speech tags.Step 6: Advanced Tokenization Techniques
In some cases, basic tokenization may not be sufficient, and more advanced techniques are required. Here are a few examples:
Byte-level Tokenization
Useful for tokenizing text data at the byte level, like in machine learning models for text generation or translation.
text = "Hello, World!"
tokens = [ord(char) for char in text]
print(tokens) # Output: [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
Subword Tokenization
Breaks down words into smaller subword units, useful for handling out-of-vocabulary words or rare words in NLP tasks.
from tokenizers import Tokenizer
tokenizer = Tokenizer(models.WordPiece('path/to/vocab.txt'))
encoded = tokenizer.encode("Tokenization")
print(encoded.ids) # Output: [2950, 8115]
Transformer-based Tokenization
Models like BERT and GPT use specific tokenization techniques like WordPiece or Byte-Pair Encoding to handle large vocabularies efficiently.
text = "Hello, World!"
tokens = [ord(char) for char in text]
print(tokens)Practice Exercise
Write a Python function that takes a text string as input and performs byte-level tokenization. The function should return a list of byte values representing each character in the string.
Show Solution
```python
def byte_level_tokenize(text):
"""Tokenizes text at the byte level, returning a list of byte values."""
byte_tokens = []
for char in text:
byte_tokens.append(ord(char))
return byte_tokens
# Example usage
text = "Hello, World!"
byte_tokens = byte_level_tokenize(text)
print(byte_tokens)
# Output: [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
```
Explanation:
- The `byte_level_tokenize` function takes a `text` string as input.
- It initializes an empty list `byte_tokens` to store the byte values.
- It iterates over each character `char` in the `text` string.
- For each character, it appends its byte value `ord(char)` to the `byte_tokens` list.
- Finally, the function returns the `byte_tokens` list containing the byte values of all characters in the input text.
- In the example usage, the function is called with the string `"Hello, World!"`, and the output shows the corresponding byte values for each character.Sign in to take Cornell notes on this lesson — they save automatically and stay with your account.