





















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






















s
CSL803: Computational Lab-II-Natural Language Processing
Sr. No. List of Experiments Page No.
1 Preprocessing of text (Tokenization, Filtration, Script Validation, Stop Word Removal, Stemming)
2 Morphological Analysis
3 N-gram model
4 POS tagging
5 Chunking
6 Named Entity Recognition
7 Virtual Lab on Word Generator
8 Mini Project based on NLP Application
actually be converted to troublinstead of trouble because the ends were just chopped off (ughh, how crude!).
There are different algorithms for stemming. The most common algorithm, which is also known to be empirically effective for English, is Porters Algorithm. Here is an example of stemming in action with Porter Stemmer:
Stopword Removal Stop words are a set of commonly used words in a language. Examples of stop words in English are “a”, “the”, “is”, “are” and etc. The intuition behind using stop words is that, by removing low information words from text, we can focus on the important words instead.
For example, in the context of a search system, if your search query is “what is text preprocessing?” , you want the search system to focus on surfacing documents that talk about text preprocessing over documents that talk about what is. This can be done by preventing all words from your stop word list from being analyzed. Stop words are commonly applied in search systems, text classification applications, topic modeling, topic extraction and others. In my experience, stop word removal, while effective in search and topic extraction systems, showed to be non-critical in classification systems. However, it does help reduce the number of features in consideration which helps keep your models decently sized. Here is an example of stop word removal in action. All stop words are replaced with a dummy character, W :
Code:
String handling: print(len("what it is what it isnt"))
s=["what","it","is" ,"what","it","isnt"]
print(len(s))
x=sorted(s)
print(s)
print(x)
d=x+s
print(d)
print (d)
Output: 23
6
['what', 'it', 'is', 'what', 'it', 'isnt']
['is', 'isnt', 'it', 'it', 'what', 'what']
['is', 'isnt', 'it', 'it', 'what', 'what', 'what', 'it', 'is', 'what', 'it', 'isnt']s
File handling (tokenization and filtering):
for line in open( "file.txt" ): for word in line.split(): if word.endswith( 'ing' ): print (word) print (len(word))
Output: eating
6
dancing
7
jumping
7
File.txt
Name Jinay Roll No.: 122 Div: B Class: B.E. Year: 2021
Experiment No. 2
Aim: To Study Morphological Analysis
Theory:
Morphological Analysis:
While performing the morphological analysis, each particular word is analyzed. Non-word tokens such as punctuation are removed from the words. Hence the remaining words are assigned categories. For instance, Ram’s iPhone cannot convert the video from .mkv to .mp4. In Morphological analysis, word by word the sentence is analyzed.So here, Ram is a proper noun, Ram’s is assigned as possessive suffix and .mkv and .mp4 is assigned as a file extension. As shown above, the sentence is analyzed word by word. Each word is assigned a syntactic category. The file extensions are also identified present in the sentence which is behaving as an adjective in the above example. In the above example, the possessive suffix is also identified. This is a very important step as the judgment of prefixes and suffixes will depend on a syntactic category for the word. For example, swims and swims are different. One makes it plural, while the other makes it a third-person singular verb. If the prefix or suffix is incorrectly interpreted then the meaning and understanding of the sentence are completely changed. The interpretation assigns a category to the word. Hence, discard the uncertainty from the word.
Regular Expression:
Regular expressions also called regex. It is a very powerful programming tool that is used for a variety of purposes such as feature extraction from text, string replacement and other string manipulations. A regular expression is a set of characters, or a pattern, which is used to find sub strings in a given string. for ex. extracting all hashtags from a tweet, getting email id or phone numbers etc.,from a large unstructured text content.
In short, if there’s a pattern in any string, you can easily extract, substitute and do variety of other string manipulation operations using regular expressions. Regular expressions are a language in itself since they have their own compilers and almost all popular programming languages support working with regexes.
Stop Word Removal:
The words which are generally filtered out before processing a natural language are called stop words. These are actually the most common words in any language (like articles, prepositions,
pronouns, conjunctions, etc) and does not add much information to the text. Examples of a few stop words in English are “the”, “a”, “an”, “so”, “what”.
Stop words are available in abundance in any human language. By removing these words, we remove the low-level information from our text in order to give more focus to the important information. In order words, we can say that the removal of such words does not show any negative consequences on the model we train for our task.
Removal of stop words definitely reduces the dataset size and thus reduces the training time due to the fewer number of tokens involved in the training.
Synonym:
The word synonym defines the relationship between different words that have a similar meaning. A simple way to decide whether two words are synonymous is to check for substitutability. Two Words are synonyms in a context if they can be substituted for each for each other without changing the meaning of the sentence.
Stemming:
Stemming is the process of reducing a word to its word stem that affixes to suffixes and prefixes or to the roots of words known as a lemma. Stemming is important in natural language understanding (NLU) and natural language processing (NLP).
Code:
Output Hows is my team doing you are supposed to be not loosing
Synonym: import nltk nltk.download('wordnet') from nltk.corpus import wordnet synonyms = [] for syn in wordnet.synsets(Machine'): for lemma in syn.lemmas(): synonyms.append(lemma.name()) print(synonyms)
Output: ['machine', 'machine', 'machine', 'machine', 'simple_machine', 'machine', 'political_machine', 'car', 'auto', 'automobile', 'machine', 'motorcar', 'machine', 'machine']
Stemming: from nltk.stem import PorterStemmer stemmer = PorterStemmer() print(stemmer.stem('eating')) print(stemmer.stem('ate'))
Output: eat
ate
Conclusion:
Thus, in the above experiment we have studied regarding morphological analysis in detail with stemming, synonym, stop word removal, regular expression and tried to implement the code and got proper output.
Name: Jinay Roll No.: 122 Div: B Class: B.E. Year: 2021 – 2022
Experiment No. 3
Aim: To study N-gram model
Theory:
Given a sequence of N-1 words, an N-gram model predicts the most probable word that might follow this sequence. It's a probabilistic model that's trained on a corpus of text. Such a model is useful in many NLP applications including speech recognition, machine translation and predictive text input.
An N-gram model is built by counting how often word sequences occur in corpus text and then estimating the probabilities. Since a simple N-gram model has limitations, improvements are often made via smoothing, interpolation and backoff.
An N-gram model is one type of a Language Model (LM), which is about finding the probability distribution over word sequences.
Consider two sentences: "There was heavy rain" vs. "There was heavy flood". From experience, we know that the former sentence sounds better. An N-gram model will tell us that "heavy rain" occurs much more often than "heavy flood" in the training corpus. Thus, the first sentence is more probable and will be selected by the model.
A model that simply relies on how often a word occurs without looking at previous words is called unigram. If a model considers only the previous word to predict the current word, then it's called bigram. If two previous words are considered, then it's a trigram model.
An n-gram model for the above example would calculate the following probability:
P('There was heavy rain') = P('There', 'was', 'heavy', 'rain') = P('There')P('was'|'There')P('heavy'|'There was')P('rain'|'There was heavy')
Since it's impractical to calculate these conditional probabilities, using Markov assumption , we approximate this to a bigram model:
P('There was heavy rain') ~ P('There')P('was'|'There')P('heavy'|'was')P('rain'|'heavy')
In speech recognition, input may be noisy and this can lead to wrong speech-to-text conversions. N-gram models can correct this based on their knowledge of the probabilities. Likewise, N-gram models are used in machine translation to produce more natural sentences in the target language.
Name :Jinay Roll No.: 122 Div: B Class: B.E. Year: 2021 – 2022
Experiment No.
Aim: To study POS tagging
Theory:
It is a process of converting a sentence to forms – list of words, list of tuples (where each tuple is having a form (word, tag)). The tag in case of is a part-of-speech tag, and signifies whether the word is a noun, adjective, verb, and so on.
Default tagging is a basic step for the part-of-speech tagging. It is performed using the DefaultTagger class. The DefaultTagger class takes ‘tag’ as a single argument. NN is the tag for a singular noun. DefaultTagger is most useful when it gets to work with most common part-of- speech tag. that’s why a noun tag is recommended.
Tagging is a kind of classification that may be defined as the automatic assignment of description to the tokens. Here the descriptor is called tag, which may represent one of the part- of-speech, semantic information and so on.
Now, if we talk about Part-of-Speech (PoS) tagging, then it may be defined as the process of assigning one of the parts of speech to the given word. It is generally called POS tagging. In simple words, we can say that POS tagging is a task of labelling each word in a sentence with its appropriate part of speech. We already know that parts of speech include nouns, verb, adverbs, adjectives, pronouns, conjunction and their sub-categories.
Most of the POS tagging falls under Rule Base POS tagging, Stochastic POS tagging and Transformation based tagging.
Rule-based POS Tagging
One of the oldest techniques of tagging is rule-based POS tagging. Rule-based taggers use dictionary or lexicon for getting possible tags for tagging each word. If the word has more than one possible tag, then rule-based taggers use hand-written rules to identify the correct tag. Disambiguation can also be performed in rule-based tagging by analyzing the linguistic features of a word along with its preceding as well as following words. For example, suppose if the preceding word of a word is article, then word must be a noun.
Stochastic POS Tagging
Markov Model (HMM), where tags are the hidden states that produced the observable output, i.e., the words.
Code:
import nltk nltk.download('averaged_perceptron_tagger') nltk.download('punkt') text = nltk.word_tokenize("And now for Everything completely Same") nltk.pos_tag(text)
Output:
[('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('Everything', 'VBG'), ('completely', 'RB'), ('Same', 'JJ')]
Conclusion:
Thus, we have studied POS Tagging in the above experiment also learned regarding different types of POS Tagging and tried to implement the code for POS Tagging and successfully executed it.
Name :Jinay Roll No.: 122 Div: B Class: B.E. Year: 2021
Experiment No. 5
Aim: To study Chunking
Theory:
Chunk extraction or partial parsing is a process of meaningful extracting short phrases from the sentence (tagged with Part-of-Speech).Chunks are made up of words and the kinds of words are defined using the part-of-speech tags. One can even define a pattern or words that can’t be a part of chuck and such words are known as chinks. A ChunkRule class specifies what words or patterns to include and exclude in a chunk.
Defining Chunk patterns: Chuck patterns are normal regular expressions which are modified and designed to match the part-of-speech tag designed to match sequences of part-of-speech tags. Angle brackets are used to specify an indiviual tag for example – to match a noun tag. One can define multiple tags in the same way.
Chunking is a process of extracting phrases from unstructured text. Instead of just simple tokens which may not represent the actual meaning of the text, its advisable to use phrases such as “ South Africa ” as a single word instead of ‘ South ’ and ‘ Africa ’ separate words.
Chunking in NLP is Changing a perception by moving a “chunk”, or a group of bits of information, in the direction of a Deductive or Inductive conclusion through the use of language. Chunking up or down allows the speaker to use certain language patterns, to utilize the natural internal process through language, to reach for higher meanings or search for more specific bits/portions of missing information.
When we “Chunk Up” the language gets more abstract and there are more chances for agreement, and when we “Chunk Down” we tend to be looking for the specific details that may have been missing in the chunk up.
As an example, if you ask the question “for what purpose cars?” you may get the answer “transport”, which is a higher chunk and more toward abstract.
Conclusion:
Thus, in the above experiment we have studies regarding chunking and tried to implement the code for same and successfully executed it.
Name Jinay Roll No.: 122 Div: B Class: B.E. Year: 2021 – 2022
Experiment No. 6
Aim: To study Named Entity Recognition
Theory:
Named Entity Recognition (NER) is a standard NLP problem which involves spotting named entities (people, places, organizations etc.) from a chunk of text, and classifying them into a predefined set of categories. Some of the practical applications of NER include:
Scanning news articles for the people, organizations and locations reported. Providing concise features for search optimization: instead of searching the entire content, one may simply search for the major entities involved. Quickly retrieving geographical locations talked about in Twitter posts.
In any text document, there are particular terms that represent specific entities that are more informative and have a unique context. These entities are known as named entities, which more specifically refer to terms that represent real-world objects like people, places, organizations, and so on, which are often denoted by proper names. A naive approach could be to find these by looking at the noun phrases in text documents. Named entity recognition (NER), also known as entity chunking/extraction, is a popular technique used in information extraction to identify and segment the named entities and classify or categorize them under various predefined classes.