



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!




import pandas as pd import nltk import re from nltk.tokenize import word_tokenize,sent_tokenize from nltk.corpus import stopwords,words from nltk.stem import PorterStemmer,WordNetLemmatizer nltk.download("punkt") nltk.download("punkt_tab") nltk.download("stopwords") nltk.download("wordnet") nltk.download("words")
imdb_url = "https://raw.githubusercontent.com/SK7here/Movie-Review-Sentiment- Analysis/refs/heads/master/IMDB-Dataset.csv" imdb = pd.read_csv(imdb_url) imdb_reviews = imdb["review"].head(15)
twitter_url = "https://raw.githubusercontent.com/tmun5718/Twitter-Sentiment- Analysis/refs/heads/master/DataSet/FinalizedFull.csv" twitter = pd.read_csv(twitter_url)
twitter.columns = twitter.columns.str.strip()
print("Twitter Dataset Columns:") print(twitter.columns.tolist())
for col in twitter.columns: if col.lower() in ["tweet", "tweets", "text", "content"]: twitter_reviews = twitter[col].astype(str).head(15) break else: raise Exception("No tweet/text column found.")
stop_words=set(stopwords.words("english")) vocabulary=set(w.lower() for w in words.words()) stemmer=PorterStemmer() lemmatizer=WordNetLemmatizer()
def preprocess(text): original=text normalized=text.lower() normalized=re.sub(r"http\S+|www\S+","",normalized) normalized=re.sub(r"@[A-Za-z0-9_]+","",normalized) normalized=re.sub(r"#","",normalized) normalized=re.sub(r"[^a-z\s]"," ",normalized) normalized=re.sub(r"\s+"," ",normalized).strip() sentences=sent_tokenize(original)
tokens=word_tokenize(normalized) filtered=[] for word in tokens: if word not in stop_words: filtered.append(word) stems=[] for word in filtered: stems.append(stemmer.stem(word)) lemmas=[] for word in filtered: lemmas.append(lemmatizer.lemmatize(word)) final=[] for word in lemmas: if word in vocabulary: final.append(word) else: final.append("") return{ "Original":original, "Normalized":normalized, "Sentences":sentences, "Tokens":tokens, "StopwordRemoved":filtered, "Stemmed":stems, "Lemmatized":lemmas, "Final":final }
def show_result(title,text): result=preprocess(text) print("="70) print(title) print("="70) print("Original Text") print(result["Original"]) print("\nSentence Segmentation") print(result["Sentences"]) print("\nTokenization") print(result["Tokens"]) print("\nStopword Removal") print(result["StopwordRemoved"]) print("\nStemming") print(result["Stemmed"]) print("\nLemmatization") print(result["Lemmatized"]) print("\nNormalized Text") print(result["Normalized"]) print("\nTrue Casing")