Linebreak not working - Python - python

Somehow the linebreaks are not working as they should.
This is what I get:
Expected:
O meu u2 2 post
http://www.yahoo.com
1 Gosto, 0 Nao gosto
<BLANKLINE>
O meu u2 post
http://www.altavista.com
1 Gosto, 0 Nao gosto
Got:
'O meu u2 2 post\nhttp://www.yahoo.com\n1 Gosto, 0 Nao Gosto\n\nO meu u2\nhttp://www.yahoo.com\n1 Gosto, 0 Nao Gosto'
This is the code used in the function.
The important parts should be the str and showRecentComments functions
class Comments():
def __init__(self, u=None, text='', link=None):
self.u = u
self.text = text
self.link = link
self.topo = None
self.fim = None
def __str__(self):
actual = self.topo
s = ''
if actual == None:
return None
while actual != None:
if actual.seg == None:
s += str(actual)
actual = actual.seg
else:
s += str(actual) + '\n' + '\n'
actual = actual.seg
return s
def add(self,comment):
if self.topo == None:
self.topo = comment
self.fim = comment
else:
comment.seg = self.topo
self.topo.ant = comment
self.topo = comment
def remove(self,comment):
actual = self.topo
if (self.topo == self.fim) and (self.topo == comment):
self.topo = None
self.fim = None
while actual!=None:
if actual == comment:
if self.topo==comment:
actual.seg.ant = None
self.topo = actual.seg
elif self.fim==comment:
actual.ant.seg = None
self.fim = actual.ant
else:
actual.seg.ant = actual.ant
actual.ant.seg = actual.seg
break
else:
actual = actual.seg
def countLike(self):
count = 0
actual = self.topo
while actual != None:
if len(actual.likeList) >= 1:
count += 1
actual = actual.seg
else:
actual = actual.seg
return count
def showRecentComments(self,n):
count = 1
actual = self.topo
sC = ''
if actual == None:
return None
while actual != None:
if count < n:
sC += str(actual) + '\n' + '\n'
count += 1
actual = actual.seg
elif count == n:
sC += str(actual)
count += 1
actual = actual.seg
elif count > n:
break
return sC
Regards, Nelson Gregório

It looks like you're looking at the representation of the string, which will show you the newline characters as \n. If you print or write to e.g. stdout (sys.stdout.write(s)) the string instead, the newlines will be expanded.

Related

How to print for loop output and change to pandas dataframe

I know this is gonna be long questions, so sorry. I'm very thankful if anyone can solve my problem.
I Have code to scoring and labeling text sentiment like this:
import re
from collections import OrderedDict
import numpy as np
class sentistrength:
def __init__(self, config=dict()):
self.negasi = [line.replace('\n','') for line in open("/content/negatingword.txt").read().splitlines()]
#create sentiment words dictionary
self.sentiwords_txt = [line.replace('\n','').split(":") for line in open("/content/sentiwords_modif.txt").read().splitlines()]
self.sentiwords_dict = OrderedDict()
for term in self.sentiwords_txt:
self.sentiwords_dict[term[0]] = int(term[1])
#create boosterwords dictionary
self.boosterwords_txt = [line.replace('\n','').split(":") for line in open("boosterwords_id.txt").read().splitlines()]
self.boosterwords_dict = OrderedDict()
for term in self.boosterwords_txt:
self.boosterwords_dict[term[0]] = int(term[1])
self.negation_conf = config["negation"]
self.booster_conf = config["booster"]
self.mean_conf = False
def senti(self,term):
try:
return self.sentiwords_dict[term]
except:
return 0
def booster(self, term):
try:
return self.boosterwords_dict[term]
except:
return 0
def cek_negationword(self, prev_term, prev_term2):
#jika kata sebelumnya (index-1) adalah kata negasi, negasikan nilai -+nya
if prev_term in self.negasi or prev_term2+" "+prev_term in self.negasi:
# print prev_term
self.score = -abs(self.score) if self.score>0 else abs(self.score)
def cek_boosterword(self,term):
booster_score = self.booster(term)
if booster_score !=0 and self.score>0: self.score += booster_score
if booster_score !=0 and self.score<0: self.score -= booster_score
def cek_consecutive_term(self, prev_term):
if self.prev_score>0 and self.score >=3: self.score+=1
if self.prev_score<0 and self.score <=-3: self.score-=1
def plural_to_singular(self, term):
return re.sub(r'([A-Za-z]+)\-\1', r'\1',term)
def classify(self):
result = "neutral"
try:
if self.mean_conf:
mean_p = np.mean(self.mean_pos)
mean_n = np.mean(self.mean_neg)
print(mean_p, mean_n)
if mean_p > mean_n:
result = "positive"
elif mean_p < mean_n and not self.is_tanya:
result = "negative"
elif mean_p < mean_n and self.is_tanya:
result = "neutral"
else:
if abs(self.sentences_max_pos) > abs(self.sentences_max_neg):
result = "positive"
elif abs(self.sentences_max_pos) < abs(self.sentences_max_neg):
result = "negative"
elif abs(self.sentences_max_pos) == abs(self.sentences_max_neg):
result = "neutral"
except:
print("error ",self.sentences_max_pos, self.sentences_max_neg)
return result
def cek_neutral_term(self,terms,i):
if terms[i-1] in self.neutral_term or terms[i+1] in self.neutral_term: self.score=1
def main(self,sentence):
self.neutral_term = ['jika','kalau']
sentences = sentence.split('.')
self.sentences_max_neg = -1
self.sentences_max_pos = 1
self.sentences_score = []
self.sentences_text = []
for sentence in sentences:
self.max_neg = -1
self.max_pos = 1
self.mean_neg = [1]
self.mean_pos = [1]
self.sentence_score=[]
terms = sentence.split()
# terms = re.split(r'[\s,.]',sentence)
terms_length = len(terms)
self.is_tanya = False
self.sentence_text = ''
# print self.max_pos, self.max_neg
#SEMUA KALIMAT YANG MEMILIKI TANDA SERU MEMILIKI +ve minimal 2
self.prev_score = 0
self.pre_max_pos = []
self.pre_max_neg = []
for i,term in enumerate(terms):
# repeated_term = ''
is_extra_char = False
plural = ''
self.score = 0
# if re.search(r'[A-Za-z\-.]+',term):
# print term
if re.search(r'([A-Za-z])\1{3,}',term):
is_extra_char = True
# repeated_term =term
if re.search(r'([A-Za-z]+)\-\1',term):
plural = term
term = self.plural_to_singular(term)
#GET SENTI SCORE#
self.score = self.senti(term)
# print "senti score",term, self.score
#NEGATION HANDLER#
if self.negation_conf and self.score !=0 and i>0:self.cek_negationword(terms[i-1],terms[i-2])
# print "negation score",term, self.score
#BOOSTERWORD HANDLER#
if self.booster_conf and self.score !=0 and i>0 and i< (terms_length 1):self.cek_boosterword(terms[i-1])
if self.booster_conf and self.score !=0 and i>=0 and i<(terms_length-1):self.cek_boosterword(terms[i+1])
# print "booster score",term, self.score
# CEK neutral term
if self.score!=0 and i>1 and i<(terms_length-2): self.cek_neutral_term(terms,i)
# if self.score!=0 and i>0 and i<(terms_length-4): self.cek_neutral_term(terms,i)
self.prev_score = self.score
if self.mean_conf and self.score>0: self.mean_pos.append(self.score)
if self.mean_conf and self.score<0: self.mean_neg.append(abs(self.score))
#GET MAX SCORE +ve/-ve
self.max_pos= self.score if self.score > self.max_pos else self.max_pos
self.max_neg= self.score if self.score < self.max_neg else self.max_neg
#insert score info current term
self.pre_max_pos.append(self.max_pos)
self.pre_max_neg.append(self.max_neg)
# print self.pre_max_pos, self.pre_max_neg
if plural !='': term = plural
self.sentence_text += ' {}'.format(term)
if self.score != 0:term = "{} [{}]".format(term, self.score)
self.sentence_score.append(term)
self.sentences_text.append(self.sentence_text)
self.sentences_score.append(" ".join(self.sentence_score))
if self.is_tanya:
self.max_neg = -1
self.sentences_max_pos = self.max_pos if self.max_pos > self.sentences_max_pos else self.sentences_max_pos
self.sentences_max_neg = self.max_neg if self.max_neg < self.sentences_max_neg else self.sentences_max_neg
# print self.sentences_max_pos, self.sentences_max_neg
sentence_result = self.classify()
# print self.sentences_text
return {"classified_text":". ".join(self.sentences_score),"tweet_text":". ".join(self.sentences_text),"sentence_score":self.sentences_score,"max_positive":self.sentences_max_pos,"max_negative":self.sentences_max_neg,"kelas":sentence_result}
config = dict()
config["negation"] = True
config["booster"] = True
senti = sentistrength(config)
print(senti.main("bagus"))
the OUTPUT is like this:
{'classified_text': 'bagus [4]', 'tweet_text': ' bagus', 'sentence_score': ['bagus [4]'], 'max_positive': 4, 'max_negative': -1, 'kelas': 'positive'}
I have thousands of texts that I want to find sentiment labels for. Is there a way to loop print so that it doesn't have to print each text one by one.
And is there a way to get the output to be a dataframe with commas as column separators? So the output look like this:
|'classified_text': 'bagus [4]'| 'tweet_text': ' bagus'| 'sentence_score': ['bagus [4]']
column continuation:
|'max_positive': 4 | 'max_negative': -1 | 'kelas': 'positive'|

use class to make dec_to_bin function

I had to hand in a python project for my school and I completely skipped it, so I'm a week late. I'm not sure if anyone can help me with this, but I know that is so easy for some people so it would be great to have someone help me because I have to hand it in as soon as possible.
The subject (translated from french to english so maybe some errrors): https://docs.google.com/document/d/17S_vqe7oqFsBjpP5ACIS5371a4t9eiOpxnPuMwlnj5Q/edit?usp=sharing
I already make part 1.
--> I need help on part 2, I already made the dec_to_bin function which return correctly binary but i don't know how to use a class to made that function like i had to do:
def dec_to_bin(n):
if n >= 1:
dec_to_bin(n // 2)
print(n % 2, end = '')
if __name__ == '__main__':
dec_val = 123456
dec_to_bin(dec_val)
My 2 previous class :
class Cellule:
def __init__(self, valeur, precedent=None, suivant=None):
self.valeur = valeur
self.precedent = precedent
self.suivant = suivant
class File:
def __init__(self):
self.longueur = 0
self.debut = None
self.fin = None
def estVide(self):
return self.longueur == 0
def enfiler(self, valeur):
if self.longueur == 0:
self.debut = self.fin = Cellule(valeur)
else:
self.fin = Cellule(valeur, self.fin)
self.fin.precedent.suivant = self.fin
self.longueur += 1
def defiler(self):
if self.longueur > 0:
valeur = self.debut.valeur
if self.longueur > 1:
self.debut = self.debut.suivant
self.debut.precedent = None
else:
self.debut = self.fin = None
self.longueur -= 1
return valeur
def __str__(self):
ch = "\nFile actuelle:\n"
cellule = self.debut
while cellule != None:
ch += str(cellule.valeur) + " "
cellule = cellule.suivant
return ch
and
class Cellule:
def __init__(self, valeur, suivant=None):
self.valeur = valeur
self.suivant = suivant
class Pile:
def __init__(self):
self.taille = 0
self.sommet = None
def estVide(self):
return self.taille == 0
def empiler(self, valeur):
self.sommet = Cellule(valeur, self.sommet)
self.taille += 1
def depiler(self):
if self.taille > 0:
valeur = self.sommet.valeur
self.sommet = self.sommet.suivant
self.taille -= 1
return valeur
def lsommet(self):
return self.sommet.valeur
def __str__(self):
ch = "\nEtat de la pile:\n"
sommet = self.sommet
while sommet != None:
ch += "|\t" + str(sommet.valeur) + "\t|" + "\n"
sommet = sommet.suivant
return ch

Python crashes with large number of inputs

I am trying to run a python program with a large number of inputs.
It works with 1k inputs, but when I try 1M it just freezes forever.
This is how I read the inputs:
This is my main:
def main():
global raiz
inputs = raw_input()
output = []
inputs = inputs.lower()
split = inputs.split(" ")
while (inputs!=""):
if (split[0] == "pass"):
if (split[2] == "r"):
novo = No(split[1].upper(), 1, True)
else:
novo = No(split[1].upper(), 1, False)
if raiz == None:
raiz = novo
else:
encontraNo(novo)
elif (split[0] == "status"):
if (raiz == None):
output.append(split[1].upper()+" NO RECORD")
else:
novo = No(split[1].upper(), 0, False)
output.append(procuraStatus(novo))
elif (split[0] == "unflag"):
if (raiz != None):
novo = No(split[1].upper(),0, False)
actualizaEstado(novo)
inputs = raw_input()
inputs = inputs.lower()
split = inputs.split(" ")
for out in output:
print out
main()
Is there a limit of inputs I can "feed" to my program?
I am using Wing IDE 5.0.
I can post the rest of my code, but I dont think that this problem is related to it but rather related with a limit of inputs that I can give to a python program
EDIT:
I've tryed running it on the console, and it worked fine with the 50k inputs.
However, when I run with 1 million inputs and left it to work (for about 2 hours), I got no results, so I stopped the program. Here is what I got in the console:
C:\Users\Tomás\Documents\Engenharia Informática\PYTHON>python TP2C.py
Traceback (most recent call last):
File "TP2C.py", line 210, in <module>
main()
C:\Users\Tomás\Documents\Engenharia Informática\PYTHON>python TP2C.py < F50K.txt
A15833 5 R
C:\Users\Tomás\Documents\Engenharia Informática\PYTHON>python TP2C.py < F1M.txt
Traceback (most recent call last):
File "TP2C.py", line 210, in <module>
main()
File "TP2C.py", line 191, in main
encontraNo(novo)
File "TP2C.py", line 84, in encontraNo
valor_matricula_noActual = ''.join(str(ord(c)) for c in so)
File "TP2C.py", line 84, in <genexpr>
valor_matricula_noActual = ''.join(str(ord(c)) for c in so)
KeyboardInterrupt
C:\Users\Tomás\Documents\Engenharia Informática\PYTHON>
This is my full code, in case you want to check it out...
class No_Avl(object):
def __init__(self, matricula, estado, numero):
self.filhoDireito = None
self.filhoEsquerdo = None
self.matricula = matricula
self.numero = numero
self.estado = estado
self.altura = 0
class Arvore_Avl(object):
global raiz
def __init__(self):
global raiz
raiz = None
def altura(self,noActual):
if (noActual == None):
return (-1)
return noActual.altura
def adicionaNoo(self, matricula, estado, numero):
global raiz
raiz = self.adicionaNo(matricula, estado, numero, raiz)
def adicionaNo(self,matricula, estado, numero, noActual):
if (noActual == None):
noActual = No_Avl(matricula, estado, numero)
elif (noActual != None):
s = matricula
valor_matricula = ''.join(str(ord(c)) for c in s)
s = noActual.matricula
valor_matricula_noActual = ''.join(str(ord(c)) for c in s)
if(valor_matricula < valor_matricula_noActual):
noActual.filhoEsquerdo = self.adicionaNo(matricula, estado, numero, noActual.filhoEsquerdo)
if (self.altura(noActual.filhoEsquerdo) - self.altura(noActual.filhoDireito) == 2):
s = matricula
valor_matricula = ''.join(str(ord(c)) for c in s)
s = noActual.matricula
valor_matricula_noActual = ''.join(str(ord(c)) for c in s)
if (valor_matricula < valor_matricula_noActual):
noActual = self.rotateWithLeftChild(noActual)
else:
noActual = self.doubleWithLeftChild(noActual)
elif (valor_matricula > valor_matricula_noActual):
noActual.filhoDireito = self.adicionaNo(matricula, estado, numero, noActual.filhoDireito)
if (self.altura(noActual.filhoDireito) - self.altura(noActual.filhoEsquerdo) == 2):
s = matricula
valor_matricula = ''.join(str(ord(c)) for c in s)
s = noActual.matricula
valor_matricula_noActual = ''.join(str(ord(c)) for c in s)
if (valor_matricula > valor_matricula_noActual):
noActual = self.rotateWithRightChild(noActual)
else:
noActual = self.doubleWithRightChild(noActual)
else:
return None
noActual.altura = max(self.altura(noActual.filhoEsquerdo), self.altura(noActual.filhoDireito)) +1
return noActual
def encontraNoo(self, matricula):
global raiz
return self.encontraNo(matricula, raiz)
def encontraNo(self, matricula, noActual):
while (noActual != None):
s = matricula
valor_matricula = ''.join(str(ord(c)) for c in s)
so = noActual.matricula
valor_matricula_noActual = ''.join(str(ord(c)) for c in so)
if (valor_matricula < valor_matricula_noActual):
noActual = noActual.filhoEsquerdo
elif (valor_matricula > valor_matricula_noActual):
noActual = noActual.filhoDireito
else:
return noActual
return None
def rotateWithLeftChild(self, k2):
k1 = k2.filhoEsquerdo
k2.filhoEsquerdo = k1.filhoDireito
k1.filhoDireito = k2
k2.altura = max(self.altura(k2.filhoEsquerdo), self.altura(k2.filhoDireito))+1
k1.altura = max(self.altura(k1.filhoEsquerdo), k2.altura) +1
return k1
def rotateWithRightChild(self, k1):
k2 = k1.filhoDireito
k1.filhoDireito = k2.filhoEsquerdo
k2.filhoEsquerdo = k1
k1.altura = max(self.altura(k1.filhoEsquerdo), self.altura(k1.filhoDireito))+1
return k2
def doubleWithLeftChild(self, k3):
k3.filhoEsquerdo = rotateWithRightChild(k3.leftChild)
return rotateWithLeftChild(k3)
def doubleWithRightChild(self, k1):
k1.filhoDireito = rotateWithLeftChild(k1.filhoDireito)
return rotateWithRightChild(k1)
def main():
global raiz
arvore = Arvore_Avl()
inputs = raw_input()
inputs = inputs.lower()
split = inputs.split(" ")
while (inputs!=""):
if (split[0] == "pass"):
if(arvore.encontraNoo(split[1]) != None):
arvore.encontraNoo(split[1]).numero += 1
arvore.encontraNoo(split[1]).estado = split[2]
else:
arvore.adicionaNoo(split[1], split[2], 1)
elif (split[0] == "status"):
mat = split[1]
if (arvore.encontraNoo(mat)!= None):
print(split[1].upper() + " "+ str(arvore.encontraNoo(split[1]).numero) + " "+arvore.encontraNoo(split[1]).estado.upper())
else:
print(split[1].upper()+" NO RECORD")
elif (split[0] == "unflag"):
if (arvore.encontraNoo(split[1]) != None):
arvore.encontraNoo(split[1]).estado = "R"
inputs = raw_input()
inputs = inputs.lower()
split = inputs.split(" ")
main()

Calculator which parses user input

import string
# Strength of operations:
# -> [] (brackets)
# 6 -> ~ (negative)
# 5 -> #, $, & (average, maximum, minimum)
# 4 -> %, ! (modulo, factorial)
# 3 -> ^ (power)
# 2 -> *, / (multiplication, division)
# 1 -> +, - (addition, subtraction)
def BinaryOperation(exp, idx):
""" Gets an expression and an index of an operator and returns a tuple with (first_value, operator, second_value). """
first_value = 0
second_value = 0
#Get first value
idx2 = idx -1
if idx2 == 0:
first_value = exp[idx2:idx]
else:
while (idx2 > 0) and (exp[idx2] in string.digits):
idx2 -=1
if (exp[idx2] in ("-")) or (exp[idx2] in string.digits):#-5*3
first_value = exp[idx2:idx]
else:#%5*3
first_value = exp[idx2+1:idx]
#Get second value
idx2 = idx +1
if exp[idx+1] not in string.digits: #If there is something like 1*+5, second_sign will be +.
idx2 += 1 #idx2 will begin from the char after the sign.
while (idx2 < len(exp)) and (exp[idx2] in string.digits):
idx2 += 1
second_value = exp[idx+1:idx2]
return (first_value, exp[idx], second_value)
def UnaryOperation(exp, idx):
""" Gets an expression and an index of an operator and returns a tuple with (operator, value). """
#Get value
idx2 = idx+1
if exp[idx+1] not in string.digits: #If there is something like ~-5, second_sign will be -.
idx2 += 1 #idx2 will begin from the char after the sign.
while (idx2 < len(exp)) and (exp[idx2] in string.digits):
idx2 +=1
return (exp[idx], exp[idx+1:idx2])
def Brackets(exp):
idx = 0
while idx < len(exp):
if exp[idx] == "[":
#Brackets
close_bracket = exp.find("]")
if close_bracket == -1:
raise Exception("Missing closing bracket.")
exp_brackets = exp[idx+1:close_bracket]
value = str(solve(exp_brackets))
exp = exp.replace("[" + exp_brackets + "]", value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level6(exp)
def Level6(exp):
idx = 0
while idx < len(exp):
if exp[idx] in ("~"):
#Negative
sub_exp = UnaryOperation(exp, idx)
value = ~int(sub_exp[1])
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level5(exp)
def Level5(exp):
idx = 0
while idx < len(exp):
if exp[idx] in ("#", "$", "&"):
#Average, Maximum and Minimum
sub_exp = BinaryOperation(exp, idx)
first_value = int(sub_exp[0])
second_value = int(sub_exp[2])
if sub_exp[1] == "#":
value = (first_value + second_value)/2
if sub_exp[1] == "$":
value = first_value if first_value > second_value else second_value
if sub_exp[1] == "&":
value = first_value if first_value < second_value else second_value
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level4(exp)
def Level4(exp):
idx = 0
while idx < len(exp):
if exp[idx] in ("%","!"):
#Modulo and Factorial
if exp[idx] == "%":
sub_exp = BinaryOperation(exp, idx)
value = int(sub_exp[0]) % int(sub_exp[2])
if exp[idx] == "!":
sub_exp = UnaryOperation(exp, idx)
value = reduce(lambda x,y:x*y, range(1, int(sub_exp[1])+1))
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level3(exp)
def Level3(exp):
idx = 0
while idx < len(exp):
if exp[idx] in ("^"):
#Power
sub_exp = BinaryOperation(exp, idx)
value = int(sub_exp[0]) ** int(sub_exp[2])
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level2(exp)
def Level2(exp):
idx = 0
while idx < len(exp):
if exp[idx] in ("*", "/"):
#Multiplication and Division
sub_exp = BinaryOperation(exp, idx)
if sub_exp[1] == "*":
value = int(sub_exp[0]) * int(sub_exp[2])
if sub_exp[1] == "/":
value = int(sub_exp[0]) / int(sub_exp[2])
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level1(exp)
def Level1(exp):
idx = 0
while idx < len(exp):
if (exp[idx] in ("+", "-")) and (idx != 0):
#Addition and Subtraction
sub_exp = BinaryOperation(exp, idx)
if sub_exp[1] == "+":
value = int(sub_exp[0]) + int(sub_exp[2])
if sub_exp[1] == "-":
value = int(sub_exp[0]) - int(sub_exp[2])
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return exp
def solve(exp):
exp = Brackets(exp)
return float(exp) if "." in exp else int(exp)
def remove_whitespace(exp):
""" Gets a string and removes all whitespaces and tabs """
exp = exp.replace(" ", "")
exp = exp.replace("\t", "")
return exp
while True:
exp = raw_input("")
exp = remove_whitespace(exp)
print solve(exp)
I have written this program after a lot of effort, and I was wondering about the efficiency of that solution and if it's neat.
So my question is, how plain is this program and is there any better way to rewrite it?
just for the point.
>>> eval(raw_input("input calculation: "))
input calculation: 1+1
2
>>> eval(raw_input("input calculation: "))
input calculation: (6*4^2)
26
>>> eval(raw_input("input calculation: "))
input calculation: (3/2.3)*4
5.2173913043478262
for an innocent program, you can use eval
but you really shouldn't use it ever. its only real use is confusing people, and being a fun novelty if you write programs fro yourself and decide you want a calculator.
there are many ways to write a calculator function.
try some of these other answers:
Python creating a calculator
Basic calculator program in python
python calculator program
If you want to check out some custom class-based evaluation engines in Python, these might help you:
Expression Evaluator (version 1 with source)
Math Evaluator (version 2 with source)
again = True
answer = ""
while again is True:
try:
expression = raw_input("Enter your expression: ")
found = False
oper = -1
operator1 = 0
operator2 = 0
while found==False:
if (expression.find("+")>0 and expression.find("+")<len(expression)-1):
found = True
oper = expression.find("+")
operator1 = float(expression[:oper])
operator2 = float(expression[oper+1:])
print "{} + {} = {}".format(operator1,operator2,operator1+operator2)
elif(expression.find("-")>0 and expression.find("-")<len(expression)-1):
found = True
oper = expression.find("-")
operator1 = float(expression[:oper])
operator2 = float(expression[oper+1:])
print "{} - {} = {}".format(operator1,operator2,operator1-operator2)
elif(expression.find("*")>0 and expression.find("*")<len(expression)-1):
found = True
oper = expression.find("*")
operator1 = float(expression[:oper])
operator2 = float(expression[oper+1:])
print "{} * {} = {}".format(operator1,operator2,operator1*operator2)
elif(expression.find("/")>0 and expression.find("/")<len(expression)-1):
found = True
oper = expression.find("/")
operator1 = float(expression[:oper])
operator2 = float(expression[oper+1:])
print "{} / {} = {}".format(operator1,operator2,operator1/operator2)
else:
oper = -1
found = False
print "Incorrect expression, please try again"
break
again = False
answer = raw_input("Try again?: ")
if(answer == "y" or answer=="yes" or answer =="Y" or answer == "YES"):
again = True
else:
again = False
print "Thank you for playing! See you next time."
break
except:
print "Failed, check your expression and try again"

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