Having problem running python code (Markov Chain project) - python

I just got into python a few weeks ago and I've been learning the language using the PyCharm software.
I was hoping to use the following code for a project:
https://github.com/eohomegrownapps/markov-music
I installed the required library, and inserted a midi file in the mentioned folder (the input folder). I'm using the following midi file:
http://www.bachcentral.com/invent/invent1.mid
Once I run the code, nothing appears in the 'compositions' folder. Can anyone tell me what I'm doing wrong? I'll post a screenshot of the code below.
Thanks a million in advance
Updated Screenshot
import random
import midi
import datetime
class Markov(object):
"""docstring for Markov"""
def __init__(self, order=2):
super(Markov, self).__init__()
self.order = order
self.chain = {}
def add(self, key, value):
if self.chain.has_key(key):
self.chain[key].append(value)
else:
self.chain[key] = [value]
def load(self, midifile):
pattern = midi.read_midifile(midifile)
# track = pattern[1]
for track in pattern:
noteslist = []
curoffset = 0
for i in track:
if i.name == "Note On" and i.data[1] != 0:
note = (i.data[0], i.data[1], i.tick + curoffset)
# note = (i.data[0],i.data[1],i.tick)
noteslist.append(note)
curoffset = 0
else:
curoffset += i.tick
if len(noteslist) > self.order:
for j in range(self.order, len(noteslist)):
t = tuple(noteslist[j - self.order:j])
print t
print noteslist[j]
self.add(t, noteslist[j])
else:
print "Corpus too short"
def generate(self, length, filename):
pattern = midi.Pattern()
# Instantiate a MIDI Track (contains a list of MIDI events)
track = midi.Track()
# Append the track to the pattern
pattern.append(track)
tick = 0
currenttuple = random.choice(self.chain.keys())
prevnote = False
for i in range(0, self.order):
if prevnote != False:
on = midi.NoteOnEvent(tick=tick, velocity=0, pitch=prevnote)
track.append(on)
on = midi.NoteOnEvent(tick=0, velocity=currenttuple[i][1], pitch=currenttuple[i][0])
track.append(on)
tick = currenttuple[i][2]
prevnote = currenttuple[i][0]
result = random.choice(self.chain[currenttuple])
# print currenttuple
for i in range(1, length):
for j in range(0, self.order):
if prevnote != False:
if tick > 5000:
tick = 5000
on = midi.NoteOnEvent(tick=tick, velocity=0, pitch=prevnote)
track.append(on)
on = midi.NoteOnEvent(tick=0, velocity=currenttuple[j][1], pitch=currenttuple[j][0])
track.append(on)
tick = currenttuple[j][2]
prevnote = currenttuple[j][0]
currenttuple = list(currenttuple)
currenttuple.pop(0)
currenttuple.append(result)
currenttuple = tuple(currenttuple)
if self.chain.has_key(currenttuple):
result = random.choice(self.chain[currenttuple])
else:
result = random.choice(self.chain[random.choice(self.chain.keys())])
# Add the end of track event, append it to the track
eot = midi.EndOfTrackEvent(tick=1)
track.append(eot)
# Print out the pattern
print pattern
# Save the pattern to disk
midi.write_midifile(filename + ".mid", pattern)
if __name__ == '__main__':
directory = "compositions"
musicdir = "input"
musicdir += "/"
logname = directory + "/" + "{:%Y-%m-%d-%H:%M:%S}_genmusic".format(datetime.datetime.now())
m = Markov(3)
print "Loading music"
inp = raw_input('Name of midi file to load or g to generate: ')
while inp != "g":
try:
m.load(musicdir + inp)
except Exception as e:
print "File not found or corrupt"
inp = raw_input('Name of midi file to load or g to generate: ')
print "Done"
print m.chain
m.generate(1000, logname)

Related

When I run my python script it shows a blank screen and disappears quickly

When I run my .py file, it quickly shows a blank black screen then disappears and does nothing. The script works fine in the editor though! The full code is down below, I know it could use some improvement but I'm just looking for answers to the blank screen for now. :) (The script is a simple genetic algorithm btw)
#!/usr/bin/python3
from fuzzywuzzy import fuzz
import random
import string
def error_msg():
print('\nSomethine went wrong!\nMake sure you typed the information correctly!')
mainF()
def mainF():
try:
while 7 == 7:
print()
stri = input('Enter string here: ')
gene = input('Enter number of generations here: ')
agen = input('Enter number of agents here: ')
muta = input('Enter chance of mutation here (0 - 1): ')
thre = input('Enter threshold here: ')
if stri == '' or gene == '' or agen == '' or thre == '' or muta == '' or stri.isdigit() or gene.isalpha() or agen.isalpha() or thre.isalpha() or muta.isalpha():
print('\nSomethine went wrong!\nMake sure you typed the information correctly!')
else:
ga(stri, len(stri), agen, gene, thre, muta)
except:
error_msg()
class Agent:
def __init__(self, length):
self.string = ''.join(random.choice(string.ascii_letters) for _ in range(length))
self.fitness = -1
def __str__(self):
return 'String: ' + str(self.string) + ', Fitness: ' + str(self.fitness) + '.'
def init_agents(population_p, length):
try:
population = int(population_p)
return [Agent(length) for _ in range(population)]
except:
error_msg()
def fitness(agents, in_str_p):
try:
in_str = in_str_p
for agent in agents:
agent.fitness = fuzz.ratio(agent.string, in_str)
return agents
except:
error_msg()
def selection(agents):
try:
agents = sorted(agents, key=lambda agent: agent.fitness, reverse=True)
print('\n'.join(map(str, agents)))
agents = agents[:int(0.2 * len(agents))]
return agents
except:
error_msg()
def crossover(agents, in_str_len_p, population_p):
try:
population = int(population_p)
in_str_len = in_str_len_p
offspring = []
for _ in range((population - len(agents)) // 2):
parent1 = random.choice(agents)
parent2 = random.choice(agents)
child1 = Agent(in_str_len)
child2 = Agent(in_str_len)
split = random.randint(0, in_str_len)
child1.string = parent1.string[0:split] + parent2.string[split:in_str_len]
child2.string = parent2.string[0:split] + parent1.string[split:in_str_len]
offspring.append(child1)
offspring.append(child2)
agents.extend(offspring)
return agents
except:
error_msg()
def mutation(agents, in_str_len_p, mutation_chance_p):
try:
mutation_chance = float(mutation_chance_p)
in_str_len = in_str_len_p
for agent in agents:
for idx, param in enumerate(agent.string):
if random.uniform(0.0, 1.0) <= mutation_chance:
agent.string = agent.string[0:idx] + random.choice(string.ascii_letters) + agent.string[idx+1:in_str_len]
return agents
except:
error_msg()
def ga(in_str_p, in_str_len_p, population_p, generations_p, threshold_p, mutation_chance_p):
mutation_chance = mutation_chance_p
threshold = int(threshold_p)
population = population_p
generations = int(generations_p)
in_str = in_str_p
in_str_len = in_str_len_p
agents = init_agents(population, in_str_len)
for generation in range(generations):
print('Generation: ' + str(generation))
agents = fitness(agents, in_str)
agents = selection(agents)
agents = crossover(agents, in_str_len, population)
agents = mutation(agents, in_str_len, mutation_chance)
if any(agent.fitness >= threshold for agent in agents):
print('Threshold met!')
mainF()
if __name__ == '__main__':
mainF()

Python program exits immediately after start

given the following code (in python):
import random
import sys
import collections
commandStr = ["addClan", "addPlayer",
"clanFight", "getMinClan"]
SUCCESS = "SUCCESS"
FAILURE = "FAILURE"
INVALID_INPUT = "INVALID_INPUT"
ClanID = dict()
playersID = dict()
ClanScore = collections.defaultdict(list)
playersClan = dict()
LosingClans = set()
Clans_count = 0;
players_count = 0;
def initline():
global ClanID, Clans_count
inLine = "init 2 0 1"
outLine = "init done."
ClanID[0] = {}
ClanID[1] = {}
Clans_count += 2
return inLine, outLine
# addClan clanID
def addClan():
global ClanID, Clans_count
clanID = random.randint(-2, 8)
inLine = "addClan %d" % (clanID)
outLine = "addClan: "
if clanID < 0:
outLine += INVALID_INPUT
elif clanID in ClanID.keys():
outLine += FAILURE
else:
ClanID[clanID] = {}
Clans_count += 1
outLine += SUCCESS
return inLine, outLine
# addPlayer playerID score clanID
def addPlayer():
global playersID, ClanID, ClanScore, playersClan, players_count
playerID = random.randint(-10, 1000)
score = random.randint(-10, 1000)
clanID = random.randint(-2, 8)
inLine = "addPlayer %d %d %d" % (playerID, score, clanID)
outLine = "addPlayer: "
if playerID < 0 or clanID < 0 or score <0:
outLine += INVALID_INPUT
elif playerID in playersID.keys() or clanID not in ClanID.keys():
outLine += FAILURE
else:
playersID[playerID] = playerID
if clanID in ClanScore.keys():
ClanScore[clanID].append(score)
else:
ClanScore[clanID] = [score]
playersClan[playerID] = clanID
ClanID[clanID][playerID] = (playersID[playerID], clanID)
players_count += 1
outLine += SUCCESS
return inLine, outLine
# getMinClan
def getMinClan():
global ClanID, LosingClans
inLine = "getMinClan"
outLine = "getMinClan: "
for Clan_id in sorted(ClanID):
if Clan_id not in LosingClans:
outLine += SUCCESS + " %d" % Clan_id
break
return inLine, outLine
def sum_n_strongest(Clan, num):
sortedClan = sorted(Clan, reverse=True)
topNum = sortedClan[:num]
Sum = 0
for element in topNum:
Sum += element
return Sum
# clanFight clan1 clan2 k1 k2
def clanFight():
global ClanID, ClanScore, LosingClans
clan1 = random.randint(-1, 8)
clan2 = random.randint(-1, 8)
k1 = random.randint(-1, 10)
k2 = random.randint(-1, 10)
inLine = "clanFight %d %d %d %d" % (clan1, clan2, k1, k2)
outLine = "clanFight: "
if k1 <= 0 or k2 <= 0 or clan1 < 0 or clan2 < 0:
outLine += INVALID_INPUT
elif clan1 not in ClanID.keys() or clan2 not in ClanID.keys() or clan1 == clan2 or len(ClanID[clan1]) < k1 or len(ClanID[clan2]) < k2:
outLine += FAILURE
elif clan1 in LosingClans or clan2 in LosingClans:
outLine += FAILURE
else:
sum1 = sum_n_strongest(ClanScore[clan1], k1)
sum2 = sum_n_strongest(ClanScore[clan2], k2)
if sum1 == sum2:
if clan1 < clan2:
LosingClans.add(clan2)
else:
LosingClans.add(clan1)
elif sum1 < sum2:
LosingClans.add(clan1)
else:
LosingClans.add(clan2)
outLine += SUCCESS
return inLine, outLine
def main():
if len(sys.argv) < 3:
print("Usage %s <lines>" % sys.argv[0])
exit(0)
lines = int(sys.argv[1])
infname = "%s.in" % sys.argv[2]
outfname = "%s.out" % sys.argv[2]
functions = [addClan, addPlayer,
getMinClan, clanFight]
with open(infname, 'wb') as infhandler:
with open(outfname, 'wb') as outfhandler:
inLine, outLine = initline()
infhandler.write(inLine + "\n")
outfhandler.write(outLine + "\n")
while lines > 0:
f = random.randint(0, len(functions)-1)
func = functions[f]
inLine, outLine = func()
if inLine is not "":
infhandler.write(inLine + "\n")
outfhandler.write(outLine + "\n")
lines -= 1
infhandler.write("quit\n")
outfhandler.write("quit done.\n")
main()
This code should create a new file while I need to give as parameters filename and numberOfLines.
But, while I trying to run this script, opened to me a black window (like a cmd) and it's closed immediately.
How can I fix it? someone know what is the problem?
Note: this code written me in a file which his name is "Test.py" , and I trying to run it with this line command: python ./Test.py <Number of Lines> <Test Name> (at least, I trying to do it while I double-click about "Test.py" but like that I said, the window closed immediately..
Follow-up question: Are you using an IDE, or are you trying to run this from the command line/command prompt?
First, check if the files exist after you run the program. It might just be that the program is running quickly enough that it only takes a couple milliseconds, and the command prompt goes away once the program terminates. If it does create a file, the program wouldn't outwardly notify you; look in your file directory and see if it did.
Second, instead of just calling main() at the end of your file, maybe try:
if __name__ == "__main__":
main()
and see if anything different happens. This bit of code is executed whenever the file is run as specifically as a script (as you're doing with the command % python Test.py <num> <fname>).

Python hangman problems

So I have my hangman almost working however, it is only placing the first correct guess on the first line, and not continuing if I guess the second letter correctly. Also, no matter what letter I guess, it always draws the head on the third letter guessed. I have it narrowed down to my getGuessLocationInPuzzle function, where my index is always printing out zero even if I have guessed my second letter. I've been staring at this code for 2 and 1/2 hours, and can't solve it. Please help!
''' Import Statements '''
from graphics import *
import copy
import random
import string
def drawGallows(window):
gallows = Rectangle(Point(300,280),Point(200,300))
gallows.draw(window)
gallows = Line(Point(250,300),Point(250,100))
gallows.draw(window)
gallows = Line(Point(250,100),Point(120,100))
gallows.draw(window)
gallows = Line(Point(120,100),Point(120,120))
gallows.draw(window)
def getPuzzle():
fh = open("puzzle.txt","r")
fileList = fh.read()
files = string.split(fileList)
puzzle = random.choice(files)
return puzzle
def drawPuzzle(length, window):
lines = Line(Point(15,275),Point(25,275))
for index in range(length):
newline = copy.copy(lines)
newline.move(20,0)
newline.draw(window)
def getGuess(entry, window):
letter = entry.getText()
return letter
def getValidGuess(Validguesses, entry, window):
guess = getGuess(entry, window)
for index in Validguesses:
if guess == index:
return guess
def createTextOverlay(guess):
textstring = ""
num = ord(guess)
for index in range(num - ord("a")):
textstring = textstring + " "
textstring= textstring + guess
for index in range(25-(ord(guess)-ord("a"))):
textstring = textstring+" "
overlay = Text(Point(150, 375), textstring)
overlay.setFace("courier")
overlay.setFill("red")
return overlay
def updateGallows(numWrongGuesses, window):
if numWrongGuesses==1:
head = Circle(Point(120,140),20)
head.draw(window)
if numWrongGuesses==2:
body = Line(Point(120,220),Point(120,160))
body.draw(window)
if numWrongGuesses==3:
arms1 = Line(Point(100,200),Point(120,160))
arms1.draw(window)
if numWrongGuesses==4:
arms2 = Line(Point(120,160),Point(140,200))
arms2.draw(window)
if numWrongGuesses==5:
leg1 = Line(Point(120,220),Point(100,250))
leg1.draw(window)
if numWrongGuesses==6:
leg2 = Line(Poin(120,220),Point(140,250))
leg2.draw(window)
def updatePuzzleDisplay(locations, letter, window):
# For each value in the locations list, print out the letter above the
# appropriate blank space.
# For each value in locations list, create a text object.
locationonspaces = 35
for index in locations:
locationonspaces = locationonspaces + 5
letterthatisguessed = Text(Point(locationonspaces, 265 ), letter)
letterthatisguessed.draw(window)
# Create text object
def getGuessLocationInPuzzle(puzzle, guess):
word = len(puzzle)
locations = []
for index in range(word):
if puzzle[index]==guess:
locations.append(index)
print guess
print index
return locations
def main():
window = GraphWin("Hangman Final", 400, 400)
drawGallows(window)
lettersToGuess = Text(Point(150, 375), "abcdefghijklmnopqrstuvwxyz")
lettersToGuess.setFace("courier")
lettersToGuess.draw(window)
guessInput = Entry(Point(250, 325), 10)
guessInput.draw(window)
puzzle = getPuzzle()
print puzzle
length = len(puzzle)
drawPuzzle(length,window)
guess = getGuess(guessInput,window)
window.getMouse()
Validguesses = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
numWrongGuesses=0
while True:
guess = getValidGuess (Validguesses,guessInput,window)
#print guess
window.getMouse
locations = getGuessLocationInPuzzle(puzzle,guess)
# print locations
if locations == []:
overlay = createTextOverlay(guess)
overlay.draw(window)
updateGallows(numWrongGuesses,window)
numWrongGuesses = numWrongGuesses + 1
else:
updatePuzzleDisplay(locations, guess, window)
overlay = createTextOverlay(guess)
overlay.draw(window)
if guess !=0:
Validguesses.remove(guess)
window.getMouse()
window.getMouse()
main()

local variable 'moodsc' referenced before assignment

In the code below I get the following error:
"local variable 'moodsc' referenced before assignment"
I'm new to programming and python. I'm struggling with interpreting other questions on the similar topic. Any context around this specific code would be helpful.
import re
import json
import sys
def moodScore(sent, myTweets):
scores = {} # initialize an empty dictionary
new_mdsc = {} # intitalize an empty dictionary
txt = {}
for line in sent:
term, score = line.split("\t") # The file is tab-delimited. "\t" means "tab character"
scores[term] = int(score) # Convert the score to an integer.
data = [] # initialize an empty list
for line in myTweets:
tweet = json.loads(line)
if "text" in tweet and "lang" in tweet and tweet["lang"] == "en":
clean = re.compile("\W+")
clean_txt = clean.sub(" ", tweet["text"]).strip()
line = clean_txt.lower().split()
moodsc = 0
pos = 0
neg = 0
count = 1
for word in range(0, len(line)):
if line[word] in scores:
txt[word] = int(scores[line[word]])
else:
txt[word] = int(0)
moodsc += txt[word]
print txt
if any(v > 0 for v in txt.values()):
pos = 1
if any(v < 0 for v in txt.values()):
neg = 1
for word in range(0, len(line)): # score each word in line
if line[word] not in scores:
if str(line[word]) in new_mdsc.keys():
moodsc2 = new_mdsc[str(line[word])][0] + moodsc
pos2 = new_mdsc[str(line[word])][1] + pos
neg2 = new_mdsc[str(line[word])][2] + neg
count2 = new_mdsc[str(line[word])][3] + count
new_mdsc[str(line[word])] = [moodsc2, pos2, neg2, count2]
else:
new_mdsc[str(line[word])] = [moodsc, pos, neg, count]
def new_dict():
for val in new_mdsc.values():
comp = val[0] / val[3]
val.append(comp)
for key, val in new_mdsc.items():
print (key, val[4])
def main():
sent_file = open(sys.argv[1])
tweet_file = open(sys.argv[2])
moodScore(sent_file, tweet_file)
# new_dict()
if __name__ == '__main__':
main()
Ok #joshp, I think you need to globalise some variables, because the error is 'moodsc referenced before assignment', I think the code only gets as far as moodsc += txt[word] but you may also have trouble with pos and neg.
Try global moodsc and pos etc. before you define moodsc and pos etc. If this doesn't work try global moodsc before moodsc += txt[word] and so forth, you may need to use global in both places for it to work, I often find that this is needed in my code, to globalise it at definition and wherever else you use it (at the start of each function and statement where it is used).

Parsing Data from live website in Python Enumerate problem!

The following script is supposed to fetch a specific line number and parse it from a live website. It works for like 30 loops but then it seems like enumerate(f) stops working correctly... the "i" in the for loop seems to stop at line 130 instead of like 200 something. Could this be due to the website I'm trying to fetch data from or something else? Thanks!!
import sgmllib
class MyParser(sgmllib.SGMLParser):
"A simple parser class."
def parse(self, s):
"Parse the given string 's'."
self.feed(s)
self.close()
def __init__(self, verbose=0):
"Initialise an object, passing 'verbose' to the superclass."
sgmllib.SGMLParser.__init__(self, verbose)
self.divs = []
self.descriptions = []
self.inside_div_element = 0
def start_div(self, attributes):
"Process a hyperlink and its 'attributes'."
for name, value in attributes:
if name == "id":
self.divs.append(value)
self.inside_div_element = 1
def end_div(self):
"Record the end of a hyperlink."
self.inside_div_element = 0
def handle_data(self, data):
"Handle the textual 'data'."
if self.inside_div_element:
self.descriptions.append(data)
def get_div(self):
"Return the list of hyperlinks."
return self.divs
def get_descriptions(self, check):
"Return a list of descriptions."
if check == 1:
self.descriptions.pop(0)
return self.descriptions
def rm_descriptions(self):
"Remove all descriptions."
self.descriptions.pop()
import urllib
import linecache
import sgmllib
tempLine = ""
tempStr = " "
tempStr2 = ""
myparser = MyParser()
count = 0
user = ['']
oldUser = ['none']
oldoldUser = [' ']
array = [" ", 0]
index = 0
found = 0
k = 0
j = 0
posIndex = 0
a = 0
firstCheck = 0
fCheck = 0
while a < 1000:
print a
f = urllib.urlopen("SITE")
a = a+1
for i, line in enumerate(f):
if i == 187:
print i
tempLine = line
print line
myparser.parse(line)
if fCheck == 1:
result = oldUser[0] is oldUser[1]
u1 = oldUser[0]
u2 = oldUser[1]
tempStr = oldUser[1]
if u1 == u2:
result = 1
else:
result = user is oldUser
fCheck = 1
user = myparser.get_descriptions(firstCheck)
tempStr = user[0]
firstCheck = 1
if result:
array[index+1] = array[index+1] +0
else:
j = 0
for z in array:
k = j+2
tempStr2 = user[0]
if k < len(array) and tempStr2 == array[k]:
array[j+3] = array[j+3] + 1
index = j+2
found = 1
break
j = j+1
if found == 0:
array.append(tempStr)
array.append(0)
oldUser = user
found = 0
print array
elif i > 200:
print "HERE"
break
print array
f.close()
Perhaps the number of lines on that web page are fewer than you think? What does this give you?:
print max(i for i, _ in enumerate(urllib.urlopen("SITE")))
Aside: Your indentation is stuffed after the while a < 1000: line. Excessive empty lines and one-letter names don't assist the understanding of your code.
enumerate is not broken. Instead of such speculation, inspect your data. Suggestion: replace
for i, line in enumerate(f):
by
lines = list(f)
print "=== a=%d linecount=%d === % (a, len(lines))
for i, line in enumerate(lines):
print " a=%d i=%d line=%r" % (a, i, line)
Examine the output carefully.

Categories