Merge branch 'metafy-social:master' into master

This commit is contained in:
Noor Ahmed 2022-10-08 04:10:27 +01:00 committed by GitHub
commit 03460ef601
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 1092 additions and 28 deletions

View File

@ -0,0 +1,17 @@
import tkinter
from time import strftime
top = tkinter.Tk()
top.title('Digital Clock')
top.resizable(0,0)
def time():
string = strftime('%H: %M: %S %p')
clockTime.config(text=string)
clockTime.after(1000, time)
clockTime = tkinter.Label(top, font=('courier new', 40),
background='white',foreground='black')
clockTime.pack(anchor='center')
time()
top.mainloop()

7
Digital-Clock/readme.md Normal file
View File

@ -0,0 +1,7 @@
# Digital Clock
## Preview
![Screenshot 2022-10-04 195233](https://user-images.githubusercontent.com/104223444/193844936-aee558c0-6b43-4096-9b9c-cc3ef23a29ed.png)
## ISSSUE
https://github.com/metafy-social/daily-python-scripts/issues/128#issue-1396619270

View File

@ -59,13 +59,6 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<sub><b>Null</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/bartick">
<img src="https://avatars.githubusercontent.com/u/69100224?v=4" width="100;" alt="bartick"/>
<br />
<sub><b>Bartick Maiti</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/PGautam27">
<img src="https://avatars.githubusercontent.com/u/92343715?v=4" width="100;" alt="PGautam27"/>
@ -73,6 +66,13 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<sub><b>P Gautam</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/bartick">
<img src="https://avatars.githubusercontent.com/u/69100224?v=4" width="100;" alt="bartick"/>
<br />
<sub><b>Bartick Maiti</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/muratonuryildirim">
<img src="https://avatars.githubusercontent.com/u/77264793?v=4" width="100;" alt="muratonuryildirim"/>
@ -159,12 +159,27 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<sub><b>Sawan Bhattacharya</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Sourodip20kar">
<img src="https://avatars.githubusercontent.com/u/104223444?v=4" width="100;" alt="Sourodip20kar"/>
<br />
<sub><b>Sourodip Kar</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Prajwol-Shrestha">
<img src="https://avatars.githubusercontent.com/u/70046321?v=4" width="100;" alt="Prajwol-Shrestha"/>
<br />
<sub><b>Prajwol Shrestha</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/yunghog">
<img src="https://avatars.githubusercontent.com/u/41548444?v=4" width="100;" alt="yunghog"/>
<br />
<sub><b>YUNGH OG</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/avyayjain">
@ -172,8 +187,7 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<br />
<sub><b>Avyay Jain</b></sub>
</a>
</td></tr>
<tr>
</td>
<td align="center">
<a href="https://github.com/lordvader501">
<img src="https://avatars.githubusercontent.com/u/60027612?v=4" width="100;" alt="lordvader501"/>
@ -188,13 +202,21 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<sub><b>Null</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/srinjoy-26">
<img src="https://avatars.githubusercontent.com/u/91176055?v=4" width="100;" alt="srinjoy-26"/>
<br />
<sub><b>Srinjoy Pati</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/NishantPacharne">
<img src="https://avatars.githubusercontent.com/u/71060551?v=4" width="100;" alt="NishantPacharne"/>
<br />
<sub><b>Nishant Pacharne</b></sub>
</a>
</td>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/thegeekyb0y">
<img src="https://avatars.githubusercontent.com/u/84658112?v=4" width="100;" alt="thegeekyb0y"/>
@ -215,8 +237,7 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<br />
<sub><b>Dishant Nagpal</b></sub>
</a>
</td></tr>
<tr>
</td>
<td align="center">
<a href="https://github.com/Mysterious-Owl">
<img src="https://avatars.githubusercontent.com/u/66870959?v=4" width="100;" alt="Mysterious-Owl"/>
@ -237,7 +258,8 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<br />
<sub><b>Aswin Shailajan</b></sub>
</a>
</td>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/jrafaaael">
<img src="https://avatars.githubusercontent.com/u/70046023?v=4" width="100;" alt="jrafaaael"/>
@ -252,14 +274,6 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<sub><b>Sauraj</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/srinjoy-26">
<img src="https://avatars.githubusercontent.com/u/91176055?v=4" width="100;" alt="srinjoy-26"/>
<br />
<sub><b>Srinjoy Pati</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/accodes21">
<img src="https://avatars.githubusercontent.com/u/101868279?v=4" width="100;" alt="accodes21"/>
@ -287,7 +301,8 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<br />
<sub><b>Sarthak Roy</b></sub>
</a>
</td>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/anjali1102">
<img src="https://avatars.githubusercontent.com/u/56559378?v=4" width="100;" alt="anjali1102"/>
@ -301,8 +316,14 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<br />
<sub><b>Nafis Adnan Mondal</b></sub>
</a>
</td></tr>
<tr>
</td>
<td align="center">
<a href="https://github.com/biv720">
<img src="https://avatars.githubusercontent.com/u/76109778?v=4" width="100;" alt="biv720"/>
<br />
<sub><b>Null</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/devtayade">
<img src="https://avatars.githubusercontent.com/u/84332795?v=4" width="100;" alt="devtayade"/>
@ -323,7 +344,8 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<br />
<sub><b>Michele Mazza</b></sub>
</a>
</td>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/mer747">
<img src="https://avatars.githubusercontent.com/u/84189502?v=4" width="100;" alt="mer747"/>
@ -344,14 +366,20 @@ Thanks a lot for spending your time helping! Keep rocking 🍻
<br />
<sub><b>Smit Shah</b></sub>
</a>
</td></tr>
<tr>
</td>
<td align="center">
<a href="https://github.com/SameerSahu007">
<img src="https://avatars.githubusercontent.com/u/29480670?v=4" width="100;" alt="SameerSahu007"/>
<br />
<sub><b>Sameer Sahu</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/shatanikmahanty">
<img src="https://avatars.githubusercontent.com/u/67138059?v=4" width="100;" alt="shatanikmahanty"/>
<br />
<sub><b>Shatanik Mahanty</b></sub>
</a>
</td></tr>
</table>
<!-- readme: contributors -end -->
<!-- readme: contributors -end -->

View File

@ -0,0 +1,18 @@
def CMYKtoRGB(c, m, y, k) :
c=float(c)/100.0
m=float(m)/100.0
y=float(y)/100.0
k=float(k)/100.0
r=round(255.0-((min(1.0, c*(1.0-k)+k))*255.0))
g=round(255.0-((min(1.0, m*(1.0-k)+k))*255.0))
b=round(255.0-((min(1.0, y*(1.0-k)+k))*255.0))
return (r,g,b)
print("Welcome To CMYK to RGB Convertor || INPUT CMYK codes and rest leave it to the convertor\n")
c=int(input("C Value: "))
m=int(input("M Value: "))
y=int(input("Y Value: "))
k=int(input("K Value: "))
print("Processing...")
print("\nYour RGB values are", CMYKtoRGB(c,m,y,k))

View File

@ -0,0 +1,9 @@
# CMKY to RGB
This is a simple python script, that allows the user to covert CMYK color values into RGB values.
## Usage
* No additional package reqd. Just the script
* Run `CMYKtoRGB.py`
* Input the CMYK values, when asked
* There you go, RGB Value is provided

View File

@ -0,0 +1,22 @@
# GitHub CLI With Python
This is a GitHub CLI utility using python. It aims to simplify daily github stats through powerful CLI ui
## How to install?
1) Open CMD (Command Prompt)
2) Run python githubCLI.py --help to see all available commands
## Available Commands
1) `python.exe main.py showall` - See all available projects for your account
2) `python.exe main.py showproject project` - See stats for your project. Replace project in command with project name
3) More commands coming soon!
## Requirements?
-[ ] Replace `ADD_YOUR_OWN` in GitHub initialization using access token from GitHub
-[ ] Install typer using `pip install typer[all]`
-[ ] Install pygithub using `pip install pygithub`
## Live action preview:
![img.png](img.png)
Hope you enjoy it! Made with ❤️ by Shatanik Mahanty

View File

@ -0,0 +1,62 @@
from github import Github
from rich.console import Console
from rich.table import Table
import typer
from rich import print
from rich.panel import Panel
from rich.console import Group
import random
app = typer.Typer()
console = Console()
# Create your token from https://github.com/settings/tokens/new
# Select repo and user scope
g = Github("ADD_YOUR_OWN")
@app.command()
def showall():
print("\n\n")
user = g.get_user()
table = Table("Repo Name", "URL", "Stars", "Open Issues", )
for repo in user.get_repos():
r = lambda: random.randint(0, 255)
color = str('#%02X%02X%02X' % (r(), r(), r()))
table.add_row("[bold " + color + "]" + repo.name, "[bold " + color + "]" + repo.url,
"[bold " + color + "]" + str(repo.stargazers_count),
"[bold " + color + "]" + str(repo.open_issues_count),
)
group = Group(
table,
)
print(Panel(group, title="[bold underline purple]All Repos of " + user.name))
print("\n\n")
@app.command()
def showproject(name: str):
repo = g.get_user().get_repo(name=name)
print("\n\n")
table = Table("Name", "Contributions")
for contributor in repo.get_contributors():
r = lambda: random.randint(0, 255)
color = str('#%02X%02X%02X' % (r(), r(), r()))
table.add_row("[bold " + color + "]" + contributor.name,
"[bold " + color + "]" + str(contributor.contributions))
group = Group(
"[bold green]Owner:[/bold green] " + "[bold]" + repo.owner.name + "[/bold]\n"
"[bold blue]URL:[/bold blue] " + "[bold]" + repo.url + "[/bold]\n"
"[bold #ecc73c]Stars:[/bold #ecc73c] " + "[bold]" + str(
repo.stargazers_count) + "[/bold]",
"[bold blue]Forks:[/bold blue] " + "[bold]" + str(repo.forks_count) + "[/bold]",
"[bold #6a5b64]Watchers:[/bold #6a5b64] " + "[bold]" + str(repo.watchers_count) + "[/bold]",
"[bold red]Issues:[/bold red] " + "[bold]" + str(repo.open_issues_count) + "[/bold]",
table,
)
print(Panel(group, title="[bold underline purple]Details of " + repo.name))
print("\n\n")
if __name__ == "__main__":
app()

BIN
scripts/GithubCLI/img.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

View File

@ -0,0 +1,5 @@
## MiniMax Algorithm
It's implemented in such way that the AI minimizes it's loss and maximizes it's winning chances.
![minimax](https://user-images.githubusercontent.com/92343715/194568346-bc6c78c3-fe22-43b9-ba25-e2f429b1b5e8.png)

View File

@ -0,0 +1,102 @@
import math
import time
from player import HumanPlayer, SmartComputerPlayer
class TicTacToe():
def __init__(self):
self.board = self.make_board()
self.current_winner = None
@staticmethod
def make_board():
return [' ' for _ in range(9)]
def print_board(self):
for row in [self.board[i*3:(i+1) * 3] for i in range(3)]:
print('| ' + ' | '.join(row) + ' |')
@staticmethod
def print_board_nums():
# 0 | 1 | 2
number_board = [[str(i) for i in range(j*3, (j+1)*3)] for j in range(3)]
for row in number_board:
print('| ' + ' | '.join(row) + ' |')
def make_move(self, square, letter):
if self.board[square] == ' ':
self.board[square] = letter
if self.winner(square, letter):
self.current_winner = letter
return True
return False
def winner(self, square, letter):
# check the row
row_ind = math.floor(square / 3)
row = self.board[row_ind*3:(row_ind+1)*3]
# print('row', row)
if all([s == letter for s in row]):
return True
col_ind = square % 3
column = [self.board[col_ind+i*3] for i in range(3)]
# print('col', column)
if all([s == letter for s in column]):
return True
if square % 2 == 0:
diagonal1 = [self.board[i] for i in [0, 4, 8]]
# print('diag1', diagonal1)
if all([s == letter for s in diagonal1]):
return True
diagonal2 = [self.board[i] for i in [2, 4, 6]]
# print('diag2', diagonal2)
if all([s == letter for s in diagonal2]):
return True
return False
def empty_squares(self):
return ' ' in self.board
def num_empty_squares(self):
return self.board.count(' ')
def available_moves(self):
return [i for i, x in enumerate(self.board) if x == " "]
def play(game, x_player, o_player, print_game=True):
if print_game:
game.print_board_nums()
letter = 'X'
while game.empty_squares():
if letter == 'O':
square = o_player.get_move(game)
else:
square = x_player.get_move(game)
if game.make_move(square, letter):
if print_game:
print(letter + ' makes a move to square {}'.format(square))
game.print_board()
print('')
if game.current_winner:
if print_game:
print(letter + ' wins!')
return letter # ends the loop and exits the game
letter = 'O' if letter == 'X' else 'X' # switches player
time.sleep(.8)
if print_game:
print('It\'s a tie!')
if __name__ == '__main__':
x_player = SmartComputerPlayer('X')
o_player = HumanPlayer('O')
t = TicTacToe()
play(t, x_player, o_player, print_game=True)

View File

@ -0,0 +1,72 @@
import math
import random
class Player:
def __init__(self, letter):
self.letter = letter
def get_move(self, game):
pass
class HumanPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
valid_square = False
val = None
while not valid_square:
square = input(self.letter + '\'s turn. Input move (0-9): ')
try:
val = int(square)
if val not in game.available_moves():
raise ValueError
valid_square = True
except ValueError:
print('Invalid square. Try again.')
return val
class SmartComputerPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
if len(game.available_moves()) == 9:
square = random.choice(game.available_moves())
else:
square = self.minimax(game, self.letter)['position']
return square
def minimax(self, state, player):
max_player = self.letter # yourself
other_player = 'O' if player == 'X' else 'X'
# first we want to check if the previous move is a winner
if state.current_winner == other_player:
return {'position': None, 'score': 1 * (state.num_empty_squares() + 1) if other_player == max_player else -1 * (
state.num_empty_squares() + 1)}
elif not state.empty_squares():
return {'position': None, 'score': 0}
if player == max_player:
best = {'position': None, 'score': -math.inf} # each score should maximize
else:
best = {'position': None, 'score': math.inf} # each score should minimize
for possible_move in state.available_moves():
state.make_move(possible_move, player)
sim_score = self.minimax(state, other_player) # simulate a game after making that move
# undo move
state.board[possible_move] = ' '
state.current_winner = None
sim_score['position'] = possible_move # this represents the move optimal next move
if player == max_player: # X is max player
if sim_score['score'] > best['score']:
best = sim_score
else:
if sim_score['score'] < best['score']:
best = sim_score
return best

View File

@ -0,0 +1,39 @@
# Screen-recorder
## Introduction
This project , records the screen , whatever you are doing and to stop recording you need to press 'Q'. It saves the video in mp4 format with the file name of date and time when it is being recorded.
## Tech stack
The project is made using python.
## Demonstration video - here is a view of the project
<https://user-images.githubusercontent.com/91176055/159889632-837f567b-d931-4069-9e0d-251b825b05a2.mp4>
## Install dependencies
- install Python 3.8.3 or above
- Further install these packages using terminal:
```bash
pip install Pillow numpy opencv-contrib-python pywin32
```
## Quick start (how to run locally)
- Clone this repository:
```bash
git clone https://github.com/metafy-social/daily-python-scripts.git
```
- Change directory:
```bash
cd daily-python-scripts
cd Screen-recorder
```
- Find main.py and run it.

View File

@ -0,0 +1,23 @@
import datetime
import cv2
from PIL import ImageGrab
import numpy as np
from win32api import GetSystemMetrics
width = GetSystemMetrics(0)
height = GetSystemMetrics(1)
time_stamp = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')
file_name = f'{time_stamp}.mp4'
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
captured_video = cv2.VideoWriter(file_name, fourcc, 20.0, (width, height))
while True:
img = ImageGrab.grab(bbox=(0, 0, width, height))
img_np = np.array(img)
img_final = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
cv2.imshow('Screen Recorder', img_final)
captured_video.write(img_final)
if cv2.waitKey(10) == ord('q'):
break

View File

@ -0,0 +1,5 @@
## Zodiac Sign Calculator
It takes in the birth month and the day as the input. It then computes it and prints the zodiac sign.
![zodiac](https://user-images.githubusercontent.com/92343715/194213601-b5f36ca7-b2de-4ec2-aad2-c3b3783bce6a.png)

View File

@ -0,0 +1,42 @@
##Takes in the month as the input
month = int(input("Enter the month number that you were born: "))
##if the month is valid the x is true. where x is a flag
if(month>0 and month <12):
print()
x=True
else:
print("wrong month, pls restart the program")
x=False
##if the flag is true then it checks the month and the date and prints the zodiac sign
if(x):
day = int(input("Enter the day you were born:"))
if month==3:
sign = "Pisces" if(day < 21) else "Aries"
elif month==4:
sign = "Aries" if(day < 20) else "Tourus"
elif month==5:
sign = "Tourus" if(day < 21) else "Gemini"
elif month==6:
sign = "Gemini" if(day < 21) else "Cancer"
elif month==7:
sign = "Cancer" if(day < 23) else "Leo"
elif month==8:
sign = "Leo" if(day < 23) else "Virgo"
elif month==9:
sign = "Virgo" if(day < 23) else "Libra"
elif month==10:
sign = "Libra" if(day < 23) else "Scorpio"
elif month==11:
sign = "Scorpio" if(day < 22) else "Sagittarius"
elif month==12:
sign = "Sagittarius" if(day < 22) else "Capricorn"
elif month==1:
sign = "Capricorn" if(day < 20) else "Aquarius"
elif month==2:
sign == "Aquarius" if(day < 19) else "Pisces"
print()
print("Your zodiac sign is "+sign)

View File

@ -0,0 +1,50 @@
# Bill Splitter
> Python script to split bills equally
## Introduction
Imagine you go to a restaurant with four of your friends. The bill will be $105. You give $50 and others chip in $40, $10 and $5 and another friend dont have change so he didn't give. Bill should have been split $21 each way so now you need to calculate who owes howmuch to whom. This python script will solve this problem. The script takes contributions (individual share) to a bill and then gives who owes how much to whom with minimum number of transaction
## Usage
Run the script.py
```bash
cd bill_splitter
python script.py
```
Enter the number of people among whom the bill is supposed to be split. eg: `2`
```
Number of participants : 2
```
Enter the name of participant and his/her contribution to the bill separated by a space. eg: `John 50`
```
Enter name and contribution of participant 1 :
John 50
Enter name and contribution of participant 2 :
Travis 100
```
Output
```
John paid $50
Travis paid $100
--------------------------------
Total pool amount : $150
Per head : $75.0
--------------------------------
John should pay $25.0 to Travis
--------------------------------
```
## Conclusion
The algorithm is designed in such a way that it will generate a result that has least number of transaction involved to achieve maximum efficiency.
## Author : Samartha | [@yunghog](https://github.com/yunghog)

View File

@ -0,0 +1,90 @@
# python script to split bills among a group
from os import system
# function to create contribution object from input string
def createContribution(s):
s = s.split(' ')
return {'name': s[0], 'contribution': int(s[1])}
# function to split bill among group
def split_bill(pool: "list[dict]") -> dict:
contribution_list = [x["contribution"] for x in pool]
total = sum(contribution_list)
each = total / len(contribution_list)
more = []
less = []
solution = []
for i in pool:
if i["contribution"] < each:
less.append(
{"name": i["name"], "contribution": each - i["contribution"]})
else:
more.append(
{"name": i["name"], "contribution": i["contribution"] - each})
for i in more:
a = i["contribution"]
m = [{"name": k["name"], "contribution": 0} for k in less]
for j in range(len(less)):
b = less[j]["contribution"]
if a == 0:
m[j]["contribution"] = 0
elif a - b == 0:
a = a - b
m[j]["contribution"] = b
less[j]["contribution"] = 0
elif a - b > 0:
a = a - b
less[j]["contribution"] = 0
m[j]["contribution"] = b
elif a - b < 0:
less[j]["contribution"] = b - a
m[j]["contribution"] = a
a = 0
solution.append({"name": i["name"], "payment": m})
return {"solution": solution, "total": total, "each": each, "pool": pool}
# function to print solution in a format
def print_solution(result: dict) -> None:
for i in result["pool"]:
print(f"{i['name']} paid ${i['contribution']}")
print("------------------------------------------------------------------")
print(f"Total pool amount : ${result['total']}")
print(f"Per head : ${result['each']}")
print("------------------------------------------------------------------")
for i in result["solution"]:
for j in i["payment"]:
if j["contribution"] > 0:
print(
f"{j['name']} should pay ${j['contribution']} to {i['name']}")
print("------------------------------------------------------------------")
def print_banner():
banner = '''
---------------------------------------------------------------------------
'''
print(banner)
system('cls')
print_banner()
pool = []
n = int(input('Number of participants : '))
for i in range(n):
print('Enter name and contribution of participant ', i+1, ' : ')
pool.append(createContribution(input()))
system('cls')
print_banner()
print_solution(split_bill(pool))

View File

@ -0,0 +1,20 @@
click==8.1.3
contourpy==1.0.5
cycler==0.11.0
fonttools==4.37.4
joblib==1.2.0
kiwisolver==1.4.4
matplotlib==3.6.0
nltk==3.7
numpy==1.23.3
packaging==21.3
pandas==1.5.0
Pillow==9.2.0
pyparsing==3.0.9
python-dateutil==2.8.2
pytz==2022.4
regex==2022.9.13
six==1.16.0
textblob==0.17.1
tqdm==4.64.1
wordcloud==1.8.2.2

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

View File

@ -0,0 +1,203 @@
import pandas as pd
import random
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
import nltk
import string
from textblob import TextBlob
import wordcloud
from matplotlib import pyplot as plt
from nltk.stem import WordNetLemmatizer
from nltk.stem import PorterStemmer
from textblob.sentiments import NaiveBayesAnalyzer
from nltk import FreqDist
# list to decide colours of positive & negative words
pos_word_list=[]
neg_word_list=[]
class SimpleGroupedColorFunc(object):
def __init__(self, color_to_words, default_color):
self.word_to_color = {word: color
for (color, words) in color_to_words.items()
for word in words}
self.default_color = default_color
def __call__(self, word, **kwargs):
return self.word_to_color.get(word, self.default_color)
class GroupedColorFunc(object):
def __init__(self, color_to_words, default_color):
self.color_func_to_words = [
(wordcloud.get_single_color_func(color), set(words))
for (color, words) in color_to_words.items()]
self.default_color_func = wordcloud.get_single_color_func(default_color)
def get_color_func(self, word):
try:
color_func = next(
color_func for (color_func, words) in self.color_func_to_words
if word in words)
except StopIteration:
color_func = self.default_color_func
return color_func
def __call__(self, word, **kwargs):
return self.get_color_func(word)(word, **kwargs)
# # function to convert a csv to string format
# def csv2string(file, negative, positive):
# s1 = "no negative"
# s2 = "no positive"
# dataset = pd.read_csv(file)
# neg = dataset[negative].head(10000)
# pos = dataset[positive].head(10000)
# neg_list = neg.tolist()
# random.shuffle(neg_list)
# pos_list = pos.tolist()
# random.shuffle(pos_list)
# final = neg_list + pos_list
# random.shuffle(final)
# review = ' '.join(final).lower()
# review = review.replace(s2,"")
# review = review.replace(s1,"")
# print('review string has been generated... Calling Wordcloud Generator')
# wordcloud_generator(review)
# function to convert a csv to string format
def csv2string(file, header):
s1 = "no negative"
s2 = "no positive"
dataset = pd.read_csv(file)
rev = dataset[header].head(10000)
rev_list = rev.tolist()
random.shuffle(rev_list)
review = ' '.join(rev_list).lower()
review = review.replace(s2,"")
review = review.replace(s1,"")
print('review string has been generated... Calling Wordcloud Generator')
wordcloud_generator(review)
# function to convert a text file to string format
def txt2string(file):
s1 = "no negative\n"
s2 = "no positive\n"
with open(file) as f:
review = f.read().lower()
review = review.replace(s2,"")
review = review.replace(s1,"")
print('review string has been generated... Calling Wordcloud Generator')
wordcloud_generator(review)
# function to determine the polarity of a given word
def word_polarity(tokens):
counter=0
for word in tokens:
testimonial = TextBlob(word, analyzer=NaiveBayesAnalyzer())
p = testimonial.sentiment.p_pos
n = testimonial.sentiment.p_neg
print(p)
print(n)
print(counter)
counter+=1
print(word)
print("~~~~~~~~~")
if p>0.5:
pos_word_list.append(word)
elif n>0.5:
neg_word_list.append(word)
# function that creates the wordcloud based on frequency of words
def calc_freq(tokens, color_function):
frequency = {}
for item in tokens:
frequency[item] = tokens.count(item)
cloud = wordcloud.WordCloud(color_func=color_function,width=800, height=400)
cloud.generate_from_frequencies(frequency)
cloud.to_file("/Users/dakshjain/Desktop/wc.png")
print("File saved in local system...")
return cloud.to_array()
def wordcloud_generator(text):
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('averaged_perceptron_tagger')
nltk.download('movie_reviews')
nltk.download('punkt')
nltk.download('omw-1.4')
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(text)
print("tokens created...")
stop_words = stopwords.words('english')
filtered_token = []
for w in tokens:
if w not in stop_words and len(w)>3:
filtered_token.append(w)
print("stop words removed...")
lemmatizer = WordNetLemmatizer()
lemmatized_filtered_token = []
for w in filtered_token:
if len(w)>3:
lemmatized_filtered_token.append(lemmatizer.lemmatize(w))
pos_tagged_token = nltk.pos_tag(lemmatized_filtered_token)
adjective_tokens_0 = []
for w in pos_tagged_token:
if w[1] == 'JJ' and len(w[0])>3:
adjective_tokens_0.append(w[0])
print("Level 1 Adjective sorting done...")
x = nltk.pos_tag(adjective_tokens_0)
adjective_tokens_1 = []
for w in x:
if w[1] == 'JJ' and len(w[0])>3:
adjective_tokens_1.append(w[0])
print("Level 2 Adjective sorting done...")
y = nltk.pos_tag(adjective_tokens_1)
adjective_tokens_2 = []
for w in y:
if w[1] == 'JJ' and len(w[0])>3:
adjective_tokens_2.append(w[0])
print("Level 3 Adjective sorting done...")
freq_dist = FreqDist(adjective_tokens_2)
common_words = freq_dist.most_common(5)
max_freq_list = []
for w in common_words:
max_freq_list.append(w[0])
print("50 most common words selected for colour sorting... Polarity Finding function called...")
word_polarity(max_freq_list)
color_to_words = {
'#00ff00': pos_word_list,
'red': neg_word_list
}
default_color = 'grey'
print("Colours associated with given words...")
grouped_color_func = GroupedColorFunc(color_to_words, default_color)
print("Calling Wordcloud Creator...")
myimage = calc_freq(adjective_tokens_2,grouped_color_func)
print("DISPLAYING THE WORDCLOUD !!")
plt.figure( figsize=(20,10), facecolor='k')
plt.imshow(myimage)
plt.axis('off')
plt.show()
# depending upon your input data call any of the 2 functions.
# For example ---
csv2string('tripadvisor_hotel_reviews.csv', 'Review')
# txt2string('file.txt')