Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7101dba

Browse files
committed
dictionary fix
1 parent 5288a75 commit 7101dba

File tree

7 files changed

+323
-10
lines changed

7 files changed

+323
-10
lines changed

data-visualization-cheatsheet.txt

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import matplotlib.pyplot as plt
2+
import pandas as pd
3+
import numpy as np
4+
5+
plt.plot(xlist, ylist)
6+
plt.show()
7+
plt.xlabel('Some label')
8+
plt.ylabel('Some label')
9+
plt.title('Some Title')
10+
11+
12+
For legend
13+
plt.plot(x, y, label="Some label")
14+
plt.legend()
15+
16+
Bar chart
17+
plt.bar(x, y, label="bars1", color="red")
18+
19+
Histogram
20+
plt.hist(xlist, bins, histtype="bar", rwidth=0.8)
21+
22+
Scatterplot
23+
plt.scatter(xlist, ylist, label="something", color="blue", marker="o", s=20)
24+
25+
StackPlot
26+
plt.plot([],[],label="y1", color="m")
27+
plt.plot([],[],label="y2", color="c")
28+
plt.plot([],[],label="y3", color="r")
29+
plt.plot([],[],label="y4", color="k")
30+
31+
plt.stackplot(xlist, y1, y2, y3, y4, colors=['m','c','r','k'])
32+
33+
pieChart
34+
plt.pie(slicesList,
35+
labels=labelList,
36+
color=colorList,
37+
startangle=90,
38+
shadow=True,
39+
explode=(0,0.1,0,0),
40+
autopct='%1.1f%%')
41+
42+
Reading from a file with numpy
43+
x, y = np.loadtext('example.txt', delimiter=',', unpack=True)

nba-foul-script.py

Lines changed: 84 additions & 0 deletions
Large diffs are not rendered by default.

nba-team-foul.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
2+
import requests, bs4
3+
from tabulate import tabulate
4+
from selenium import webdriver
5+
6+
7+
#Team Dictionary helps to make urls for boxscore and for full-forms of abbrevation of teams
8+
teamDict = {
9+
"ATL": ["Atlanta Hawks","01", "atlanta-hawks-", "/r/atlantahawks", "1610612737", "Hawks"],
10+
"NJN": ["Brooklyn Nets", "02", "boston-celtics-", "/r/bostonceltics", "1610612738", "Nets"],
11+
"BOS": ["Boston Celtics", "17", "brooklyn-nets-","/r/gonets", "1610612751", "Celtics"],
12+
"CHA": ["Charlotte Hornets", "30", "charlotte-hornets-","/r/charlottehornets", "1610612766", "Hornets"],
13+
"CHI": ["Chicago Bulls", "04", "chicago-bulls-","/r/chicagobulls", "1610612741", "Bulls"],
14+
"CLE": ["Cleveland Cavaliers", "05", "cleveland-cavaliers-","/r/clevelandcavs", "1610612739", "Cavaliers"],
15+
"DAL": ["Dallas Mavericks", "06", "dallas-mavericks-","/r/mavericks", "1610612742", "Mavericks"],
16+
"DEN": ["Denver Nuggets", "07", "denver-nuggets-","/r/denvernuggets", "1610612743", "Nuggets"],
17+
"DET": ["Detroit Pistons", "08", "detroit-pistons-", "/r/detroitpistons", "1610612765", "Pistons"],
18+
"GSW": ["Golden State Warriors", "09", "golden-state-warriors-", "/r/warriors", "1610612744", "Warriors"],
19+
"HOU": ["Houston Rockets", "10", "houston-rockets-", "/r/rockets", "1610612745", "Rockets"],
20+
"IND": ["Indiana Pacers", "11", "indiana-pacers-", "/r/pacers", "1610612754", "Pacers"],
21+
"LAC": ["Los Angeles Clippers", "12", "los-angeles-clippers-", "/r/laclippers", "1610612746", "Clippers"],
22+
"LAL": ["Los Angeles Lakers", "13", "los-angeles-lakers-", "/r/lakers", "1610612747", "Lakers"],
23+
"MEM": ["Memphis Grizzlies", "29", "memphis-grizzlies-", "/r/memphisgrizzlies", "1610612763", "Grizzlies"],
24+
"MIA": ["Miami Heat", "14", "miami-heat-", "/r/heat", "1610612748", "Heat"],
25+
"MIL": ["Milwaukee Bucks", "15", "milwaukee-bucks-", "/r/mkebucks", "1610612749", "Bucks"],
26+
"MIN": ["Minnesota Timberwolves", "16", "minnesota-timberwolves-", "/r/timberwolves", "1610612750", "Timberwolves"],
27+
"NOH": ["New Orleans Pelicans", "03", "new-orleans-pelicans-", "/r/nolapelicans", "1610612740", "Pelicans"],
28+
"NYK": ["New York Knicks", "18", "new-york-knicks-", "/r/nyknicks", "1610612752", "Knicks"],
29+
"OKC": ["Oklahoma City Thunder", "25", "oklahoma-city-thunder-", "/r/thunder", "1610612760", "Thunder"],
30+
"ORL": ["Orlando Magic", "19", "orlando-magic-", "/r/orlandomagic", "1610612753", "Magic"],
31+
"PHI": ["Philadelphia 76ers", "20", "philadelphia-76ers-", "/r/sixers", "1610612755", "76ers"],
32+
"PHX": ["Phoenix Suns", "21", "phoenix-suns-", "/r/suns", "1610612756", "Suns"],
33+
"POR": ["Portland Trail Blazers", "22", "portland-trail-blazers-", "/r/ripcity", "1610612757", "Trail Blazers"],
34+
"SAC": ["Sacramento Kings", "23", "sacramento-kings-", "/r/kings", "1610612758", "Kings"],
35+
"SAS": ["San Antonio Spurs", "24", "san-antonio-spurs-", "/r/nbaspurs", "1610612759", "Spurs"],
36+
"TOR": ["Toronto Raptors", "28", "toronto-raptors-", "/r/torontoraptors", "1610612761", "Raptors"],
37+
"UTA": ["Utah Jazz", "26", "utah-jazz-", "/r/utahjazz", "1610612762", "Jazz"],
38+
"WAS": ["Washington Wizards", "27", "washington-wizards-", "/r/washingtonwizards", "1610612764, ", "Wizards"]
39+
}
40+
41+
teamShort = []
42+
baseUrl = "https://www.basketball-reference.com"
43+
allData = {}
44+
45+
def requestSoup(url):
46+
res = requests.get(url)
47+
return bs4.BeautifulSoup(res.text, 'html.parser')
48+
49+
for each in teamDict.keys():
50+
teamShort.append(each)
51+
52+
driver = webdriver.Chrome()
53+
54+
driver.get("https://www.basketball-reference.com/leagues/NBA_2019.html")
55+
thisYearStatsPage = bs4.BeautifulSoup(driver.page_source, "html.parser")
56+
tableContainer = thisYearStatsPage.find("table", {"id":"team-stats-per_game"})
57+
personalFoulTbodyContainer = tableContainer.find("tbody")
58+
dataRow = personalFoulTbodyContainer.findAll("tr")
59+
for eachRow in dataRow:
60+
allData[str(eachRow.find("a").text)] = [eachRow.find("td", {"data-stat":"pf"}).text]
61+
62+
tableContainer = thisYearStatsPage.find("table", {"id":"opponent-stats-per_game"})
63+
opponentFoulTbodyContainer = tableContainer.find("tbody")
64+
dataRow = opponentFoulTbodyContainer.findAll("tr")
65+
for eachRow in dataRow:
66+
allData[str(eachRow.find("a").text)].append(eachRow.find("td", {"data-stat":"opp_pf"}).text)
67+
68+
69+
70+
print(allData)
71+
driver.quit()

reddit-nba-bot/all-game-threads.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import json
77
from datetime import date, timedelta, datetime
88
import time
9+
import traceback
910
import random
1011
import praw
1112
import requests
@@ -16,10 +17,10 @@
1617
teamDict = {
1718
"ATL": ["Atlanta Hawks","01", "atlanta-hawks-",
1819
"/r/atlantahawks", "1610612737", "Hawks"],
19-
"BKN": ["Brooklyn Nets", "02", "boston-celtics-",
20-
"/r/bostonceltics", "1610612738", "Nets"],
21-
"BOS": ["Boston Celtics", "17", "brooklyn-nets-",
22-
"/r/gonets", "1610612751", "Celtics"],
20+
"BKN": ["Brooklyn Nets", "17", "brooklyn-nets-",
21+
"/r/gonets", "1610612751", "Nets"],
22+
"BOS": ["Boston Celtics", "02", "boston-celtics-",
23+
"/r/bostonceltics", "1610612738", "Celtics"],
2324
"CHA": ["Charlotte Hornets", "30", "charlotte-hornets-",
2425
"/r/charlottehornets", "1610612766", "Hornets"],
2526
"CHI": ["Chicago Bulls", "04", "chicago-bulls-",
@@ -350,10 +351,15 @@ def editGameThread(boxScoreData, bodyText, date, teamDict):
350351
(basicGameData["vTeam"]["score"]
351352
!= basicGameData["hTeam"]["score"])):
352353
#if all of the above condition met then
353-
redditGamePostList[i]["postResponse"].edit(editGameThread(
354+
try:
355+
redditGamePostList[i]["postResponse"].edit(editGameThread(
354356
dataBoxScore,
355357
redditGamePostList[i]["bodyText"],
356358
dateToday, teamDict))
359+
except IndexError:
360+
traceback.print_exc()
361+
except KeyError:
362+
traceback.print_exc()
357363
else:
358364
basicGameData = dataBoxScore["basicGameData"]
359365
redditGamePostList[i]["postResponse"].edit(editGameThread(
@@ -381,4 +387,5 @@ def editGameThread(boxScoreData, bodyText, date, teamDict):
381387
print(title)
382388
time.sleep(60)
383389
if all(game is None for game in redditGamePostList):
390+
redditGamePostList = []
384391
break

reddit-nba-bot/nba-boxscore-comment-bot.py

Lines changed: 109 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
import requests
44
import json
55
from datetime import date, timedelta
6+
import bs4, requests
7+
import sys
8+
from tabulate import tabulate
69

710
#Team Dictionary helps to make urls for boxscore and for full-forms of abbrevation of teams
811
teamDict = {
@@ -37,6 +40,20 @@
3740
"UTA": ["Utah Jazz", "26", "utah-jazz-", "http://np.reddit.com/r/utahjazz"],
3841
"WAS": ["Washington Wizards", "27", "washington-wizards-", "http://np.reddit.com/r/washingtonwizards"]
3942
}
43+
44+
45+
#Save the name of Channel and link in the list here
46+
allChannels = [
47+
['MLG Highlights', 'https://www.youtube.com/channel/UCoh_z6QB0AGB1oxWufvbDUg'],
48+
['Moar Highlights', 'https://www.youtube.com/channel/UCeW4gzPrv1sHkXyKQgQGRFw'],
49+
['House of Highlights', 'https://www.youtube.com/channel/UCqQo7ewe87aYAe7ub5UqXMw'],
50+
['FreeDawkins', 'https://www.youtube.com/channel/UCEjOSbbaOfgnfRODEEMYlCw'],
51+
['DownToBuck', 'https://www.youtube.com/channel/UCNaGVvWvXaYI16vAxQUfq3g'],
52+
['ESPN', 'https://www.youtube.com/user/ESPN'],
53+
['CliveNBAParody', 'https://www.youtube.com/user/RealKingClive'],
54+
['NBA on ESPN', 'https://www.youtube.com/user/TheNBAonESPN']
55+
]
56+
4057
#getting a reddit instance by giving appropiate credentials
4158
reddit = praw.Reddit(username = config.username,
4259
password = config.password,
@@ -123,6 +140,97 @@ def findPlayerName(dataPlayersLeague, playerId):
123140
gamesList = list(map(int, s.split()))
124141

125142
for gameIndex in gamesList:
143+
144+
highlightList = []
145+
requiredHighlightList = []
146+
for submission in reddit.subreddit('nba').search("site:streamable.com", sort="new", time_filter="day"):
147+
highlightList.append(submission)
148+
149+
for i in range(len(highlightList)):
150+
print(str(i) + " " + highlightList[i].title)
151+
152+
s = input("Choose the highlights(s) (by index) you want to add in Post Game Thread: ")
153+
highlightIndexList = list(map(int, s.split()))
154+
155+
for each in highlightIndexList:
156+
requiredHighlightList.append(highlightList[each])
157+
158+
youtubeHighlightList = []
159+
#Number of videos to list; Keep it less than 30
160+
listVid = 15
161+
#Dictionary for non bmp characters
162+
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
163+
164+
print("List of Channels:")
165+
166+
for i in range(len(allChannels)):
167+
print(str(i+1) + ". " + str(allChannels[i][0]))
168+
channelIndex = 1
169+
while channelIndex != 0:
170+
channelIndex = int(input("Choose one of the channel by index number(Press 0 to exit): "))
171+
if channelIndex > 0 and channelIndex < (len(allChannels) + 1):
172+
res = requests.get(str(allChannels[channelIndex - 1][1]) + '/videos')
173+
soup = bs4.BeautifulSoup(res.text, 'html.parser')
174+
allVids = soup.findAll('div', {'class':'yt-lockup-content'})
175+
wantedVids = allVids[:listVid]
176+
vidTitles = []
177+
vidLinks = []
178+
vidDuration = []
179+
vidUploaded = []
180+
for each in wantedVids:
181+
vidATag = each.find('a')
182+
vidSpanTag = each.find('span')
183+
vidLiTag = each.findAll('li')
184+
vidTitles.append(str(vidATag.text).translate(non_bmp_map))
185+
vidLinks.append("https://youtube.com" + str(vidATag['href']))
186+
vidDuration.append(str(vidSpanTag.text).replace("- Duration: ", ""))
187+
vidUploaded.append(vidLiTag[1].text)
188+
vidIndex = range(1, listVid + 1)
189+
header = ["Index", "Title", "Duration", "Uploaded"]
190+
table = zip(vidIndex, vidTitles, vidDuration, vidUploaded)
191+
print(tabulate((table), header, tablefmt="grid"))
192+
# this will make a list of space seperated value (for eg. 5 4 2 1) and download in that order
193+
choosenVids = list(map(int, input("Enter index of all videos you want to download(Space seperated values): ").split()))
194+
for each in choosenVids:
195+
if int(each)>listVid or int(each)<1:
196+
print("Index out of bound")
197+
else:
198+
url = str(vidLinks[int(each-1)])
199+
title = str(vidTitles[int(each-1)])
200+
uploader = allChannels[channelIndex - 1][0]
201+
youtubeHighlightList.append([url, title, uploader])
202+
203+
elif channelIndex == 0:
204+
print("Thanks")
205+
else:
206+
print("Please choose a number from the index or press 0 to exit")
207+
208+
body = '''###Game Highlights:
209+
210+
- [**Full Game Highlights**]({0})
211+
212+
Source: {1}'''.format(str(youtubeHighlightList[0][0]), str(youtubeHighlightList[0][2]))
213+
214+
for i in range(1, len(youtubeHighlightList)):
215+
body += '''
216+
217+
- [**{0}**]({1})
218+
219+
Source: {2}'''.format(str(youtubeHighlightList[i][1]), str(youtubeHighlightList[i][0]), str(youtubeHighlightList[i][2]))
220+
221+
body += '''
222+
223+
###Play Highlights:
224+
225+
'''
226+
227+
for each in requiredHighlightList:
228+
body += '''- [**{0}**]({1})
229+
230+
[Source](https://www.reddit.com{2}): /u/{3}
231+
232+
'''.format(each.title, each.url, each.permalink, each.author)
233+
126234
game = gameIndex-1
127235
if game in range(len(tabulateList)):
128236

@@ -137,7 +245,7 @@ def findPlayerName(dataPlayersLeague, playerId):
137245
yahooUrl = "http://sports.yahoo.com/nba/" + teamDict[tabulateList[game]["visitorTeam"]][2] + teamDict[tabulateList[game]["homeTeam"]][2] + date + teamDict[tabulateList[game]["homeTeam"]][1]
138246

139247
#Body of reddit post starts here
140-
body = '''
248+
body += '''
141249
||
142250
|:-:|
143251
|[](/''' + tabulateList[game]["visitorTeam"] + ") **" + tabulateList[game]["visitorTeamScore"] + " - " + tabulateList[game]["homeTeamScore"] + "** [](/" + tabulateList[game]["homeTeam"] + ''')|

reddit-nba-bot/reddit-boxscore-bot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
#Team Dictionary helps to make urls for boxscore and for full-forms of abbrevation of teams
1313
teamDict = {
1414
"ATL": ["Atlanta Hawks","01", "atlanta-hawks-", "http://np.reddit.com/r/atlantahawks", "1610612737"],
15-
"BKN": ["Brooklyn Nets", "02", "boston-celtics-", "http://np.reddit.com/r/bostonceltics", "1610612738"],
16-
"BOS": ["Boston Celtics", "17", "brooklyn-nets-","http://np.reddit.com/r/gonets", "1610612751"],
15+
"BOS": ["Boston Celtics", "02", "boston-celtics-", "http://np.reddit.com/r/bostonceltics", "1610612738"],
16+
"BKN": ["Brooklyn Nets", "17", "brooklyn-nets-","http://np.reddit.com/r/gonets", "1610612751"],
1717
"CHA": ["Charlotte Hornets", "30", "charlotte-hornets-","http://np.reddit.com/r/charlottehornets", "1610612766"],
1818
"CHI": ["Chicago Bulls", "04", "chicago-bulls-","http://np.reddit.com/r/chicagobulls", "1610612741"],
1919
"CLE": ["Cleveland Cavaliers", "05", "cleveland-cavaliers-","http://np.reddit.com/r/clevelandcavs", "1610612739"],

reddit-nba-bot/test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@
1414
allPosts = []
1515
postTime = []
1616

17-
for submission in reddit.subreddit('nba').search("post game thread", sort='top'):
17+
for submission in reddit.subreddit('nba').search("ryan sanders", sort='top'):
1818
date = datetime.datetime.fromtimestamp(submission.created_utc)
1919
dif = datetime.datetime.utcnow() - date
20-
if dif<datetime.timedelta(days=1000):
20+
if dif<datetime.timedelta(days=300):
2121
allPosts.append(submission)
2222

2323
for each in allPosts:

0 commit comments

Comments
 (0)