w3resource

NLTK Tokenize: Find parenthesized expressions in a given string and divides into a sequence of substrings

NLTK Tokenize: Exercise-9 with Solution

Write a Python NLTK program to find parenthesized expressions in a given string and divides the string into a sequence of substrings.

Sample Solution:

Python Code:

from nltk.tokenize import SExprTokenizer
text = '(a b (c d)) e f (g)'
print("\nOriginal Tweet:")
print(text)
print(SExprTokenizer().tokenize(text))
text = '(a b) (c d) e (f g)'
print("\nOriginal Tweet:")
print(text)
print(SExprTokenizer().tokenize(text))
text = '[(a b (c d)) e f (g)]'
print("\nOriginal Tweet:")
print(text)
print(SExprTokenizer().tokenize(text))
print(text)
print(SExprTokenizer().tokenize(text))
text = '{a b {c d}} e f {g}'
print("\nOriginal Tweet:")
print(text)
print(SExprTokenizer().tokenize(text))

Sample Output:

Original Tweet:
(a b (c d)) e f (g)
['(a b (c d))', 'e', 'f', '(g)']

Original Tweet:
(a b) (c d) e (f g)
['(a b)', '(c d)', 'e', '(f g)']

Original Tweet:
[(a b (c d)) e f (g)]
['[', '(a b (c d))', 'e', 'f', '(g)', ']']
[(a b (c d)) e f (g)]
['[', '(a b (c d))', 'e', 'f', '(g)', ']']

Original Tweet:
{a b {c d}} e f {g}
['{a b {c d}} e f {g}']

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python NLTK program that will read a given text through each line and look for sentences. Print each sentence and divide two sentences with “==============”.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Get the Key Whose Value Is Maximal in a Dictionary:

>>> model_scores = {'model_a': 100, 'model_z': 198, 'model_t': 150}
>>> # workaround
>>> keys, values = list(model_scores.keys()), list(model_scores.values())
>>> keys[values.index(max(values))]
'model_z'
>>> # one-line
>>> max(model_scores, key=model_scores.get)
'model_z'