|
import multiprocessing
|
|
import os
|
|
import pandas as pd
|
|
import requests
|
|
from bs4 import BeautifulSoup
|
|
import re
|
|
import string
|
|
import nltk
|
|
import time
|
|
nltk.download('punkt')
|
|
nltk.download('stopwords')
|
|
nltk.download('wordnet')
|
|
nltk.download('cmudict')
|
|
from nltk.corpus import stopwords
|
|
from nltk.tokenize import sent_tokenize, word_tokenize
|
|
from nltk.corpus import cmudict
|
|
|
|
folderpath = r'C:\Users/suwes/SentimentEngine/'
|
|
textfile_path = f"{folderpath}inputtext/"
|
|
stopword_path = f"{folderpath}StopWords/"
|
|
masterdict_path = f"{folderpath}MasterDictionary/"
|
|
|
|
def createdf():
|
|
inputxlsx = os.path.join(folderpath, "Input.xlsx")
|
|
dfxlsx = pd.read_excel(inputxlsx)
|
|
print(dfxlsx)
|
|
df_urls = dfxlsx['URL']
|
|
|
|
return dfxlsx
|
|
|
|
df = createdf()
|
|
|
|
def extract(df):
|
|
|
|
def extract_urltext(url):
|
|
response = requests.get(url)
|
|
soup = BeautifulSoup(response.content, 'html.parser')
|
|
article_title = soup.find('title').get_text()
|
|
article_content = soup.find('div', class_= 'td-pb-span8 td-main-content')
|
|
article_text = ''
|
|
if article_content:
|
|
for para in article_content.find_all(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']):
|
|
article_text += para.get_text()
|
|
|
|
|
|
return article_title, article_text
|
|
|
|
|
|
|
|
|
|
|
|
for index, row in df.iterrows():
|
|
url = row['URL']
|
|
url_id = row['URL_ID']
|
|
article_title, article_text = extract_urltext(url)
|
|
|
|
filename = f"{folderpath}inputtext/{url_id}.txt"
|
|
with open(filename, 'w', encoding = 'utf-8') as file:
|
|
file.write(article_title+ '\n\n' +article_text)
|
|
print(f"text saved to file {filename}")
|
|
|
|
|
|
extract(df)
|
|
|
|
def transform(df):
|
|
|
|
|
|
def read_stopwords(stopword_folder):
|
|
stopwords = set()
|
|
filenames = os.listdir(stopword_folder)
|
|
|
|
for filename in filenames:
|
|
filepath = os.path.join(stopword_folder, filename)
|
|
|
|
with open(filepath, 'r', encoding= 'utf-8', errors='ignore') as file:
|
|
stopwords.update(map(str.strip, file.readlines()))
|
|
return stopwords
|
|
|
|
stopwords = read_stopwords(stopword_path)
|
|
|
|
|
|
def clean_stopwords(text, stopwords):
|
|
|
|
words = word_tokenize(text)
|
|
|
|
cleaned_words = [word for word in words if word.lower() not in stopwords]
|
|
|
|
cleaned_text = ' '.join(cleaned_words)
|
|
return cleaned_text
|
|
|
|
|
|
def clean_stopwords_directory(directory, stopwords):
|
|
|
|
filenames = os.listdir(directory)
|
|
|
|
for filename in filenames:
|
|
filepath = os.path.join(directory, filename)
|
|
|
|
with open(filepath, 'r', encoding='utf-8', errors='ignore') as file:
|
|
text = file.read()
|
|
|
|
cleaned_text = clean_stopwords(text, stopwords)
|
|
|
|
with open(filepath, 'w', encoding= 'utf-8', errors='ignore') as file:
|
|
file.write(cleaned_text)
|
|
print(f"cleaned text from {filename}")
|
|
|
|
clean_stopwords_directory(textfile_path, stopwords)
|
|
|
|
def create_posneg_dict(masterdict_path, stopwords):
|
|
poswords = set()
|
|
negwords = set()
|
|
|
|
with open(os.path.join(masterdict_path, 'positive-words.txt'), 'r', encoding='utf-8', errors='ignore') as file:
|
|
for line in file:
|
|
words = line.strip().split()
|
|
for word in words:
|
|
if word.lower() not in stopwords:
|
|
poswords.add(word.lower())
|
|
|
|
with open(os.path.join(masterdict_path, 'negative-words.txt'), 'r', encoding='utf-8', errors='ignore') as file:
|
|
for line in file:
|
|
words = line.strip().split()
|
|
for word in words:
|
|
if word.lower() not in stopwords:
|
|
negwords.add(word.lower())
|
|
return poswords, negwords
|
|
|
|
positivewords, negativewords = create_posneg_dict(masterdict_path, stopwords)
|
|
|
|
|
|
return stopwords, positivewords, negativewords
|
|
|
|
|
|
stopwords, positivewords, negativewords = transform(df)
|
|
|
|
|
|
result_df = pd.DataFrame()
|
|
def loadoutput(folderpath, result_df):
|
|
exceloutfilepath = f"{folderpath}Output.xlsx"
|
|
result_df.to_excel(exceloutfilepath, index=False)
|
|
print(f"output file saved to {exceloutfilepath}")
|
|
print(f"analysis time: {int((time.time() - starttime)//3600)} hours {int(((time.time() - starttime)%3600)//60)} minutes {int((time.time() - starttime)%60)} seconds")
|
|
|
|
|
|
def runengine(df, stopwords, files_subset, dflist):
|
|
|
|
|
|
def calculate_positivescore(words, positivewords):
|
|
positivescore = sum(1 for word in words if word.lower() in positivewords)
|
|
return positivescore
|
|
|
|
def calculate_negativescore(words, negativewords):
|
|
negativescore = (sum(-1 for word in words if word.lower() in negativewords))*(-1)
|
|
return negativescore
|
|
|
|
|
|
def calc_readibility(words, sentences):
|
|
|
|
avg_sentencelen = len(words)/len(sentences) if sentences else 0
|
|
|
|
complexwords = [word for word in words if syllable_count(word)>2]
|
|
percent_complexwords = len(complexwords)/len(words)*100 if words else 0
|
|
|
|
fog_index = 0.4*(avg_sentencelen + percent_complexwords)
|
|
return avg_sentencelen, percent_complexwords, fog_index
|
|
|
|
|
|
def avg_wordspersentence(words, sentences):
|
|
if len(sentences) > 0:
|
|
averagewords = len(words)/len(sentences)
|
|
return averagewords
|
|
else: return 0
|
|
|
|
|
|
def syllable_count(word):
|
|
d = cmudict.dict()
|
|
if word.lower() in d:
|
|
return [len(list(y for y in x if y[-1].isdigit())) for x in d[word.lower()]][0]
|
|
else:
|
|
return 0
|
|
def complexwords_count(words):
|
|
complexwords = [word for word in words if syllable_count(word)>2]
|
|
return len(complexwords)
|
|
|
|
|
|
def cleanwords_count(words, stopwords):
|
|
punctuations = set(string.punctuation)
|
|
cleaned_words = [word.lower() for word in words if word.lower() not in stopwords and word.lower() not in punctuations]
|
|
return len(cleaned_words)
|
|
|
|
|
|
|
|
def vowel_syllable(word):
|
|
vowels = 'aeiouy'
|
|
count = 0
|
|
endings = 'es', 'ed', 'e'
|
|
|
|
word = word.lower().strip()
|
|
if word.endswith(endings):
|
|
word = word[:-2]
|
|
elif word.emdswith('le'):
|
|
word = word[:-2]
|
|
endings = ''
|
|
elif word.endswith('ing'):
|
|
word = word[:-3]
|
|
endings = ''
|
|
|
|
if len(word)<=3:
|
|
return 1
|
|
for index, letter in enumerate(word):
|
|
if letter in vowels and (index ==0 or word[index -1] not in vowels):
|
|
count +=1
|
|
|
|
if word.endswith('y') and word[-2] not in vowels:
|
|
count +=1
|
|
return count
|
|
|
|
def vowel_syllable_perword(words):
|
|
total_syllables = sum(syllable_count(word) for word in words)
|
|
return total_syllables
|
|
|
|
|
|
def count_pronouns(text):
|
|
pattern = r'\b(?:I|we|my|ours|us)\b'
|
|
|
|
matches = re.findall(pattern, text, flags=re.IGNORECASE)
|
|
|
|
matches_fin = [matches for match in matches if match.lower() != 'us']
|
|
countpron = len(matches_fin)
|
|
return countpron
|
|
|
|
|
|
def calc_avg_wordlength(words):
|
|
total_chars = sum(len(word) for word in words)
|
|
total_words = len(words)
|
|
if total_words != 0:
|
|
avg_wordlength = total_chars/total_words
|
|
else: avg_wordlength = 0
|
|
return avg_wordlength
|
|
|
|
def appendtodf(url_idkey, calc_values, process_df):
|
|
rowindex = df[df['URL_ID'] == url_idkey].index
|
|
if not rowindex.empty:
|
|
idx_toupdate = rowindex[0]
|
|
|
|
new_row = pd.DataFrame(columns=process_df.columns)
|
|
|
|
new_row.loc[0, process_df.columns[:2]] = df.loc[idx_toupdate, ['URL_ID', 'URL']]
|
|
|
|
for col, value in calc_values.items():
|
|
new_row[col] = value
|
|
|
|
process_df = process_df._append(new_row, ignore_index=True)
|
|
print(f"Result updated for {url_idkey}")
|
|
else:
|
|
print(f"!not found {url_idkey}")
|
|
return process_df
|
|
|
|
|
|
process_df = pd.DataFrame(columns=df.columns)
|
|
for filename in files_subset:
|
|
filepath = os.path.join(textfile_path, filename)
|
|
|
|
url_idkey = re.search(r'blackassign\d{4}', filepath).group()
|
|
if os.path.isfile(filepath):
|
|
with open(filepath, 'r', encoding='utf-8', errors='ignore') as file:
|
|
text = file.read()
|
|
|
|
words = word_tokenize(text)
|
|
sentences = sent_tokenize(text)
|
|
totalwords = len(words)
|
|
|
|
|
|
positive_score = calculate_positivescore(words, positivewords)
|
|
print(f"{filename} positive socre: {positive_score}")
|
|
|
|
|
|
negative_score = calculate_negativescore(words, negativewords)
|
|
print(f"{filename} negative socre: {negative_score}")
|
|
|
|
|
|
polarity_score = (positive_score - negative_score)/((positive_score+negative_score)+0.000001)
|
|
print(f"{filename} polarity socre: {polarity_score}")
|
|
|
|
|
|
subjectivity_score = (positive_score+negative_score)/((totalwords)+0.000001)
|
|
print(f"{filename} subjectivity socre: {subjectivity_score}")
|
|
|
|
|
|
avg_sentencelen, percent_complexwords, fog_index = calc_readibility(words, sentences)
|
|
print(f"{filename} avg sentencelength: {avg_sentencelen}")
|
|
|
|
print(f"{filename} percentage of complex words: {percent_complexwords}")
|
|
|
|
print(f"{filename} Fog Index: {fog_index}")
|
|
|
|
|
|
avg_wordper_sentence = avg_wordspersentence(words, sentences)
|
|
print(f"{filename} avg words per sentence: {avg_wordper_sentence}")
|
|
|
|
|
|
complexword_count = complexwords_count(words)
|
|
print(f"{filename} complex words count: {complexword_count}")
|
|
|
|
|
|
cleanword_count = cleanwords_count(words, stopwords)
|
|
print(f"{filename} clean words count: {cleanword_count}")
|
|
|
|
|
|
syllablecount_perword = vowel_syllable_perword(words)
|
|
print(f"{filename} syllable count per word: {syllablecount_perword}")
|
|
|
|
|
|
pronouns_count = count_pronouns(text)
|
|
print(f"{filename} personal pronouns count: {pronouns_count}")
|
|
|
|
|
|
avg_wordlength = calc_avg_wordlength(words)
|
|
print(f"{filename} avg word length: {avg_wordlength}")
|
|
else: print(f"df not updated for {filename}!")
|
|
|
|
calc_values = {
|
|
"POSITIVE SCORE": positive_score,
|
|
"NEGATIVE SCORE": negative_score,
|
|
"POLARITY SCORE": polarity_score,
|
|
"SUBJECTIVITY SCORE": subjectivity_score,
|
|
"AVG SENTENCE LENGTH": avg_sentencelen,
|
|
"PERCENTAGE OF COMPLEX WORDS": percent_complexwords,
|
|
"FOG INDEX": fog_index,
|
|
"AVG NUMBER OF WORDS PER SENTENCE": avg_wordper_sentence,
|
|
"COMPLEX WORD COUNT": complexword_count,
|
|
"WORD COUNT": cleanword_count,
|
|
"SYLLABLE PER WORD": syllablecount_perword,
|
|
"PERSONAL PRONOUNS": pronouns_count,
|
|
"AVG WORD LENGTH": avg_wordlength
|
|
}
|
|
try:
|
|
process_df = appendtodf(url_idkey,calc_values, process_df)
|
|
except Exception as e:
|
|
print(e)
|
|
print(process_df)
|
|
dflist.append(process_df)
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
starttime = time.time()
|
|
files_toprocess = os.listdir(textfile_path)
|
|
|
|
num_processes = multiprocessing.cpu_count()
|
|
print(str(num_processes)+ " CPUs")
|
|
files_perprocess = len(files_toprocess) // num_processes
|
|
print(files_perprocess)
|
|
|
|
processes = []
|
|
|
|
manager = multiprocessing.Manager()
|
|
dflist = manager.list()
|
|
|
|
for i in range(num_processes):
|
|
try:
|
|
start = i*files_perprocess
|
|
end = (i+1)*files_perprocess if i != num_processes-1 else len(files_toprocess)
|
|
files_subset = files_toprocess[start:end]
|
|
|
|
p = multiprocessing.Process(target=runengine, args =(df, stopwords, files_subset, dflist))
|
|
processes.append(p)
|
|
p.start()
|
|
except Exception as e:
|
|
print(e)
|
|
|
|
print("waiting for all processes to end...")
|
|
for i in processes:
|
|
print(i)
|
|
for process in processes:
|
|
try:
|
|
process.join()
|
|
except Exception as e:
|
|
print(e)
|
|
for i in processes:
|
|
print(i)
|
|
|
|
print(str(len(dflist))+" result dataframes obtained.")
|
|
result_df = pd.concat(dflist, ignore_index=True)
|
|
result_df = result_df.sort_values(by='URL_ID')
|
|
print(result_df)
|
|
|
|
loadoutput(folderpath, result_df)
|
|
|