0% found this document useful (0 votes)
6 views7 pages

Python Regular Expressions & Morphology

The document outlines two experiments focused on implementing regular expressions and a morphological parser in Python. Experiment 3A covers various regular expressions for text normalization, including programming exercises to match specific string patterns. Experiment 3B involves parsing morphological features of words using a predefined list and demonstrates the application of these concepts in Python.

Uploaded by

shruti
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views7 pages

Python Regular Expressions & Morphology

The document outlines two experiments focused on implementing regular expressions and a morphological parser in Python. Experiment 3A covers various regular expressions for text normalization, including programming exercises to match specific string patterns. Experiment 3B involves parsing morphological features of words using a predefined list and demonstrates the application of these concepts in Python.

Uploaded by

shruti
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Experiment 3A

Aim : To implement the various regular expressions in Python


Theory :
Regular expressions can be used to specify strings extracted from a document. Regular Expressions
play an important role to a set of tasks collectively called text normalization. Normalizing text means
converting it to a more convenient, standard form. The simplest kind of regular expression is a
sequence of simple characters. To search for woodchuck, we type /woodchuck/.Regular expressions
are case [Link] the use of the square braces [ and ],the string of characters inside the braces
specifies a disjunction of characters to match. Kleene * means “zero or more occurrences of the
immediately previous character or regular expression”. So /a*/ means “any string of zero or more
as”. The special character period (/./) is a wildcard expression that matches any single character
(except a carriage return). Anchors are special characters that anchor regular expressions to
particular places in a string. The most common anchors are the caret ˆ and the dollar sign $.
Disjunction Operator which is also called pipe symbol (|) is used to select either of the strings. E.g
/cat|dog/ implies cat or dog.
Operator Precedence Hierarchy

Programming Exercises
1. Write a Python program that matches a string that has an a followed by zero or more b's.
2. Write a Python program that matches a string that has an a followed by one or more b's
3. Write a Python program to find sequences of lowercase letters joined with a underscore.
4. Write a Python program to find sequences of one upper case letter followed by lower case
letters
5. Write a Python program that matches a word containing 'z'.
6. Write a Python program that matches a word containing 'z', not start or end of the word
7. Write a Python program to match a string that contains only upper and lowercase letters,
numbers, and underscores.
8. Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given
string.
9. Write a Python program to search some literals strings in a string.
Sample text : 'The quick brown fox jumps over the lazy dog.'
Searched words : 'fox', 'dog', 'horse'
10. Write a Python program to replace whitespaces with an underscore and vice versa.
11. Write a Python program to separate and print the numbers of a given string.
12. Write a Python program to find all words starting with 'a' or 'e' in a given string.
13. Write a Python program to abbreviate 'Road' as 'Rd.' in a given string.
14. Write a Python program to remove multiple spaces in a string.
15. Write a Python program to remove everything except alphanumeric characters from a string.
Code:
import re
def check_match(regex, s):
if [Link](regex, s): print(f'"{s}": Match Found')
else: print(f'"{s}": Match Not Found')
s1 = 'coiwc ac qm-cm'; s2 = 'frcgergcoweng'
regex = r'ab*?' # Matches a followed by zero or more b's
check_match(regex, s1); check_match(regex, s2)
s1 = 'coiwc abbbb qm-cm'; s2 = 'frcgergcoweng'
regex = r'ab*' # Matches a followed by one or more b's
check_match(regex, s1); check_match(regex, s2)
s1 = 'asd_asd';s2 = 'ASD_ASD'
regex = r'[a-z]+\_[a-z]+' # Matches sequence of lowercase letters joined by underscore
check_match(regex, s1);check_match(regex, s2)
s1 = 'Adsfvw';s2 = 'scqgr'
regex = r'[A-Z][a-z]*' ;check_match(regex, s1);check_match(regex, s2)
s1 = 'adza';s2 = 'dff';regex = r'z' # Matches sequence that contains 'z'
check_match(regex, s1);check_match(regex, s2)
s1 = 'ononxzbg';s2 = 'zfwrgvz zowgbf'
regex = r'\Bz\B' # Matches a word containing 'z' not start or end of the word
check_match(regex, s1);check_match(regex, s2)
s1 = 'Ax_9';s2 = 'nn@#'
regex = r'^[a-zA-Z0-9_]+$'
check_match(regex, s1);check_match(regex, s2)
s1 = 'hnowvieugh 98 bvp';s2 = '769485674'
regex = r'[0-9]{1,3}' # Matches the numbers (0-9) of length between 1 to 3 in a given string
check_match(regex, s1);check_match(regex, s2)
s1 = 'ninh fox pinh';s2 = 'mjr[gme]'
word = 'fox';regex = r'fox' # Matches the numbers (0-9) of length between 1 to 3 in a given string
check_match(regex, s1);check_match(regex, s2)
s1 = 'niuh ifg_no8';s1 = [Link](' ', '_')
s2 = [Link]('_', ' ');print(s1 + ' : ' + s2)
s1 = 'io 1 non5 8 nguogn 78';print([Link]('\D+', s1))
s1 = 'argr npwoeihn nvpwrhtn eionpoj';s2 = 'mnhpo oinptb enpin'
regex = r'[ae]\w+';print([Link](regex, s1))
print([Link](regex, s2));s1 = 'pvn Road ibo'
print([Link]('Road', 'Rd'));s1 = 'oihur ftu n0guy '
print([Link](' ', ''));s1 = 'pihnm$%,noieg02980'
regex = r'[\w]+';print([Link](regex).sub('', s1))

Output:
"coiwc ac qm-cm": Match Found
"frcgergcoweng": Match Not Found
"coiwc abbbb qm-cm": Match Found
"frcgergcoweng": Match Not Found
"asd_asd": Match Found
"ASD_ASD": Match Not Found
"Adsfvw": Match Found
"scqgr": Match Not Found
"adza": Match Found
"dff": Match Not Found
"ononxzbg": Match Found
"zfwrgvz zowgbf": Match Not Found
"Ax_9": Match Found
"nn@#": Match Not Found
"hnowvieugh 98 bvp": Match Found
"769485674": Match Found
"ninh fox pinh": Match Found
"mjr[gme]": Match Not Found
niuh_ifg_no8 : niuh ifg no8
['', '1', '5', '8', '78']
['argr', 'eihn', 'eionpoj']
['enpin']
pvn Rd ibo
oihurftun0guy
Pihnmnoieg02980

Experiment 3B
Aim : To implement the morphological parser in Python
Theory :
Finite-State Morphological Parsing
Our goal will be to take input forms like those in the first columns and produce output forms like
those in the second column shown below:

Morphological Features specify additional information about the stem. For example the feature +N
means that the word is a noun; +Sg means it is singular, +Pl that it is plural.

0 1 2 3 4 5 6 7 8 9
cat dog park face day year ear eye
cats dogs parks faces days years ears eyes
bus life fly box wolf inch church glass
buses lives flies boxes wolves inches churches glasses
bush waltz brush leaf crush story baby party
bushes waltzes brushes leaves crushes stories babies parties
walk run merge map dip speak bring make
walks runs merges maps dips speaks brings makes
walking running merging mapping dipping speaking bringing making
walked ran merged mapped dipped spoke brought made
mouse goose child person foot tooth woman man
mice geese children people feet teeth women men

0 1 2 3 4 5 6 7 8 9
sheep deer monkey donkey zoo key boy guy book car
sheeps deers monkeys donkeys zoos keys boys guys books cars
zoo radio stereo video tomato country knife piano berry lady
zoos radios stereos videos tomatoes countries knives pianos berries ladies
hero quiz fish series kangaroo species city potato fairy echo
kangaroo
heroes quizzes fishes series s species cities potatoes fairies echoes
come go think write take say blow drink eat hug
comes goes thinks writes takes says blows drinks eats hugs
coming going thinking writing taking saying blowing drinking eating hugging
came went thought wrote tok said blew drank ate hugged

Programming Exercises
Write a Python program that parses the string given above according to your digits of your roll
number. For Example : 01 Will parse the words from

0 1
cat deer
cats deers
bus radio
buses radios
bush quiz
bushes quizzes
walk go
walks goes
walking going
walked went
mouse
mice
Code:
import re
from [Link] import wordnet as wn
import nltk
words = ['cat', 'cats', 'bus', 'buses', 'bush', 'bushes', 'walk', 'walks',
'walking', 'walked', 'mouse', 'mice', 'ear', 'ears', 'church',
'churches', 'baby', 'babies', 'bring', 'brings', 'bringing', 'brought', 'woman', 'women']
def get(word):
return [Link](w)[0].pos()
def print_word(word, sg):
if sg: print(f'{w} = {word} + {get(word).upper()} + SG')
else: print(f'{w} = {word} + {get(word).upper()} + PL')
for w in words:
sg = True
if w == 'women': sg = False
elif w == 'bus': word = w; sg = True
elif w == 'mice': word = w; sg = False
elif [Link]('ies'): word = w[:-3] + 'y'; sg = False
elif [Link]('es'): word = w[:-2]; sg = False
elif [Link]('s'): word = w[:-1]; sg = False
else: word = w; sg = True
print_word(word, sg)
Output:
cat = cat + N + SG
cats = cat + N + PL
bus = bus + N + SG
buses = bus + N + PL
bush = bush + N + SG
bushes = bush + N + PL
walk = walk + N + SG
walks = walk + N + PL
walking = walking + N + SG
walked = walked + V + SG
mouse = mouse + N + SG
mice = mice + N + PL
ear = ear + N + SG
ears = ear + N + PL
church = church + N + SG
churches = church + N + PL
baby = baby + N + SG
babies = baby + N + PL
bring = bring + V + SG
brings = bring + V + PL
bringing = bring + N + SG
brought = brought + V + SG
woman = woman + N + SG
women = women + N + PL

Conclusion
In the above experiment, we learnt about Regular Expressions and Morphological Parser, and
implemented the same using python

You might also like