codes banner image

Python projects

This section contains a range of smaller scale/one-off Python projects.

1. Text Generator: Markov model (1st Order)

This program is able to generate text of a desied length based on an input text. It woks with only 1st Order Markov model. Input text is split into words, the words are loaded into a transition table. From there, generate a text that is relatively similar to the initial text input.

import random

# take input text from a file
with open("romeo_and_juliet.txt", encoding="utf8") as f:
	input = f.read()

# spilt the words
words = input.split(' ')

# replace EOL with whitespace
input = input.replace("\n", " ")

# make into a model using py dict
model = {}
for i in range(len(words)-1):
	state1 = words[i] # state 
	state2 = words[i + 1] # transition

	if state1 not in model:
		model[state1] = [] # create new key in dict 
	model[state1].append(state2)

# generate an output
output = ""
output_length = 15

# take model.keys(), convert into a list and pick a random value
s = random.choice(list(model.keys()))

for i in range(output_length):
	if s not in model: # reached the end of the transition table
		break
	s = random.choice(model[s])
	output = output + " " + s

# print to a text file
with open("output.txt", "a") as outFile:
	outFile.write(output + "\n\n#####\n\n")

print(output) 
								

2. Sentiment analysis: TextBlob

This is a very simple and straightforward sentiment analysis bot. It uses TextBlob's sentiment polartity method. It's relatively straightforward; It provides a quick and dirty sentiment analysis without taking into account the contextor relationship between individual words, hence why "Super duper sad" would be classified as "neutral".
This code is based on Federico Azzurro's tutorial (@Indently on YT) on Udemy with heavy modification from me:

https://www.udemy.com/course/great-python-projects/learn/lecture/38212564#overview

from textblob import TextBlob
from dataclasses import dataclass

@dataclass
class Mood:
	"""class used to store the mood and polarity of a message"""
	emoji: str
	sentiment: float

def get_mood(input_text: str, *, sensitivity: float) -> Mood:
	"""
	input_text: user generated message to analyse
	sensitivity: a value which needs to be surpassed in order 
	for the program to return happy treshold
	"""

	# get the polarity using TextBlob's sentiment.polarity
	polarity: float = TextBlob(input_text).sentiment.polarity
	
	# define treshod of happy to unhappy
	happy_treshold: float = sensitivity
	unhappy_treshold: float = sensitivity * -1

	if polarity >= happy_treshold:
		return Mood("😁", polarity)
	elif polarity <= unhappy_treshold:
		return Mood("â˜šī¸", polarity)
	else:
		return Mood("😐", polarity)
	
def run_bot():
	print("\nGreetings! please enter some text to analyse.")
	while True:
		user_input: str = input("\nYou: ")
		mood: Mood = get_mood(user_input, sensitivity=0.3)
		print(f"Mood: {mood.emoji}, (polarity: {mood.sentiment})\n")
	
if __name__ == "__main__":
	run_bot()