I'm having this error:
File "zzz.py", line 70
else:
^
SyntaxError: invalid syntax
The line which causes the problem is marked with a comment in the code:
def FileParse(self, table_file):
vars={}
tf = open(table_file, 'r')
for line in tf:
if line.startswith("#") or line.strip() == "": pass
elif line.startswith("n_states:"):
self.n_states = str(line[9:].strip())
elif line.startswith("neighborhood:"):
self.neighborhood = str(line[13:].strip())
elif line.startswith("symmetries:"):
self.symmetries = str(line[11:].strip())
elif line.startswith("var "):
line = line[4:]
ent = line.replace('=',' ').\
replace('{',' ').\
replace(',',' ').\
replace(':',' ').\
replace('}',' ').\
replace('\n','').split()
vars[ent[0]] = []
for e in ent[1:]:
if e in vars: vars[ent[0]] += vars[e]
else:
vars[ent[0].append(int(e))]
else:
rule = line.strip().split(",")
for k in vars.keys():
if k in rule:
for i in vars[k]:
change = rule.replace(k, i)
change = [int(x) for x in change]
w.rules.append(Rule(change[:5],change[5])
else: # line which causes the problem
rule = [int(x) for x in rule]
w.rules.append(Rule(rule[:5],rule[5]))
tf.close()
self.parse_status "OK"
return w.rules
w.rules is variable which is assigned to "World" class.
To be honest I have no idea why I get this. Before everything was fine and now that error shows up after adding some extra instructions in other indented blocks.
Any ideas?
Because you left out a closing brace
w.rules.append(Rule(change[:5],change[5]) )
The previous line, w.rules.append(Rule(change[:5],change[5]), is missing a close paren.
While you're at it, there is another typo. You probably want:
self.parse_status "OK"
To be:
self.parse_status = "OK"
Remove extra spaces/lines and re-indent the if/else statements. This worked for me.
(I tried the other solutions here but none worked. My braces were fine.)
Related
When I run the following code in IDLE Python 3.9 the expected output was coming but when I run the code in code playground (Online IDE) the code was not showing expected output but instead throwing some error.
The error:
Traceback (most recent call last):
File "main.py", line 28, in <module>
non_adjacent(input())
EOFError: EOF when reading a line
The code:
def non_adjacent(words:str):
words_list = words.split()
result = []
l = len(words_list)
for i in range(l-2):
for j in range(i+2, l):
tmp1 = words_list[i]
tmp2 = words_list[j]
index_tmp1 = [k for k in range(l) if words_list[k]==tmp1]
index_tmp2 = [m for m in range(l) if words_list[m]==tmp2]
not_adj = True
for el1 in index_tmp1:
for el2 in index_tmp2:
if abs(el1 - el2) == 1:
not_adj = False
tmp = sorted([tmp1, tmp2])
if tmp not in result and not_adj:
result.append(tmp)
for el in sorted(result):
print(*el)
while True:
non_adjacent(input())
To host it online, you will need to use repl.it, I dont know if code playground supports input(), anyways goto repl.it and create an account. then a new repl. Then choose "Python" and give it a name. then post this code:
def non_adjacent(words:str):
words_list = words.split()
result = []
l = len(words_list)
for i in range(l-2):
for j in range(i+2, l):
tmp1 = words_list[i]
tmp2 = words_list[j]
index_tmp1 = [k for k in range(l) if words_list[k]==tmp1]
index_tmp2 = [m for m in range(l) if words_list[m]==tmp2]
not_adj = True
for el1 in index_tmp1:
for el2 in index_tmp2:
if abs(el1 - el2) == 1:
not_adj = False
tmp = sorted([tmp1, tmp2])
if tmp not in result and not_adj:
result.append(tmp)
for el in sorted(result):
print(*el)
while True:
non_adjacent(input("Please enter words sperated by a space: "))
Working Example:
https://replit.com/#craftit7/EmailHelp1#main.py
EOFError is raised when one of the built-in functions input() or raw_input() hits an end-of-file condition (EOF) without reading any data. This error is sometimes experienced while using online IDEs. This occurs when we have asked the user for input but have not provided any input in the input box.
Code playground is an online IDE.
This code is appearing to give me an error to my arguments i don't know what i have done wrong in this code. When attempting to run a binary search inside tkinter using python 2.7 The programs works fine if i don't use the gui just line code. This is the code I have based my program on
http://www.pythonschool.net/data-structures-algorithms/binary-search/
The error is: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in call return self.func(*args) TypeError: binarySearch() takes exactly 2 arguments (0 given)
from Tkinter import *
import csv
with open('scoresRecord.csv', 'rb') as f:
reader = csv.reader(f)
your_list = list(reader)
root = Tk()
root.resizable(0,0)
root.title("Score Board")
def binarySearch(myitem,myList):
found = False
bottom = 0
top = len(myList)-1
while bottom<=top and not found:
middle = (bottom+top)//2
if myList[middle]== myitem:
found = True
elif myList[middle] < myitem:
bottom = middle + 1
else:
top = middle-1
return found
if __name__=="__main__":
Scorelist = [row[0] for row in your_list]
Dismissallist =[row[1] for row in your_list] # create a list of only the dismissal
Venuelist =[row[2] for row in your_list] # create a list of only the venue
item = int(input(entScore.get()))
Scorelist = map(int, Scorelist)
rowPos = Scorelist.index(item)
isitFound = binarySearch(item,Scorelist)
if isitFound:
Score= Scorelist[rowPos]
Dismissal= Dismissallist[rowPos]
Venue= Venuelist[rowPos]
else:
Score= ("Not Found")
Dismissal= ("Not Found")
Venue= ("Not Found")
numScoreLbl.configure(text=Score)
numDismissal.configure(text=Dismissal)
outVenue.configure(text=Venue)
#==========GUI Section==================#
First of all, make sure your list is ordered, otherwise the results may be wrong.
Second, do this
Scorelist = list(map(int, Scorelist))#convert to list
isitFound = binarySearch(item,Scorelist)
Although, if you are using .index method, then you can do something like this for better performance:
try:
index = Scorelist.index(item)
isitFound = True
except ValueError:
isitFound = False
It takes out the binary search part, but you were using .index anyways. So this is better. Hope it helps :)
I am working on a program to count anglicisms in German texts and everything works fine except when trying to output the results to a text file (at the bottom of the code). Here's my code so far:
from collections import Counter
import os.path
print('='*50)
print('Welcome to the ANGLICISM COUNTER 5000')
while True:
print('='*50)
lines, blanklines, sentences, words, setnum = 0,0,0,0,1
setname = input('Please enter setname: ')
listOfAnglicisms = open('anglicisms.txt').read().split()
listOfGermanWords = open('haufigste.txt').read().split()
anglicisms = []
falsepositive = []
def derivatesFromAnglicism(word):
return any([word.startswith(a) for a in listOfAnglicisms])
while os.path.isfile(str(setname+str(setnum)+".txt")) == True:
textf = open(setname+str(setnum)+'.txt')
for line in textf:
line = line.lower()
lines+=1
if line.startswith('\n'):
blanklines+=1
else:
sentences += line.count('.') + line.count('!') + line.count('?')
words += len(line.split(None))
anglicisms.extend([word for word in line.split() if derivatesFromAnglicism(word)])
anglicisms = [x for x in anglicisms if x not in listOfGermanWords]
setnum+=1
textf.close()
print('='*50)
print('Lines : ',lines)
print('Blanklines : ',blanklines)
print('Sentences : ',sentences)
print('Words: : ',words)
print('Anglicisms : ',len(anglicisms))
print('Words until anglicism : ',int(words)/len(anglicisms)-1)
print('All anglicisms :\n',Counter(anglicisms))
print('='*50)
while falsepositive != 'n':
falsepositive = input('Please enter a false positive or "n" to continue: ')
if falsepositive == 'n':
pass
else:
while falsepositive in anglicisms:
anglicisms.remove(falsepositive)
print('='*50)
print('Lines : ',lines)
print('Blanklines : ',blanklines)
print('Sentences : ',sentences)
print('Words: : ',words)
print('Anglicisms : ',len(anglicisms))
print('Words until anglicism : ',int(words)/len(anglicisms)-1)
print('All anglicisms :\n',Counter(anglicisms))
print('='*50)
results = open(setname+'.txt', 'w')
results.write(
('='*50)+
'\n'+
setname+'\n'+
'Lines : '+lines+'\n'+
'Blanklines : '+blanklines+'\n'+
'Sentences : '+sentences+'\n'+
'Words: : '+words+'\n'+
'Anglicisms : '+len(anglicisms)+'\n'+
'Words until anglicism : '+int(words)/len(anglicisms)-1+'\n'+
'All anglicisms :\n'+Counter(anglicisms)+'\n'+
('='*50)+
'\n'
)
results.close()
And this is the error I get:
Traceback (most recent call last):
File "C:\...\anglicism_counter_5000.py", line 81, in <module>
('='*50)+
TypeError: Can't convert 'int' object to str implicitly
I have tried using str() on the variables but it didn't help. Does anybody know how to use write() properly, so this error won't occur again?
The error message is a little confusing. It's quoting the line ('='*50), but the program actually crashes at
'Lines : '+lines+'\n'+
(I didn't count the lines, though.)
lines is an integer. SO you'd need to wrap it with str(...). Same for the other integers you're printing.
So I am learning python and redoing some old projects. This project involves taking in a dictionary and a message to be translated from the command line, and translating the message. (For example: "btw, hello how r u" would be translated to "by the way, hello how are you".
We are using a scanner supplied by the professor to read in tokens and strings. If necessary I can post it here too. Heres my error:
Nathans-Air-4:py1 Nathan$ python translate.py test.xlt test.msg
Traceback (most recent call last):
File "translate.py", line 26, in <module>
main()
File "translate.py", line 13, in main
dictionary,count = makeDictionary(commandDict)
File "/Users/Nathan/cs150/extra/py1/support.py", line 12, in makeDictionary
string = s.readstring()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 105, in readstring
return self._getString()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 251, in _getString
if (delimiter == chr(0x2018)):
ValueError: chr() arg not in range(256)
Heres my main translate.py file:
from support import *
from scanner import *
import sys
def main():
arguments = len(sys.argv)
if arguments != 3:
print'Need two arguments!\n'
exit(1)
commandDict = sys.argv[1]
commandMessage = sys.argv[2]
dictionary,count = makeDictionary(commandDict)
message,messageCount = makeMessage(commandMessage)
print(dictionary)
print(message)
i = 0
while count < messageCount:
translation = translate(message[i],dictionary,messageCount)
print(translation)
count = count + 1
i = i +1
main()
And here is my support.py file I am using...
from scanner import *
def makeDictionary(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst = []
token = s.readtoken()
count = 0
while (token != ""):
lyst.append(token)
string = s.readstring()
count = count+1
lyst.append(string)
token = s.readtoken()
return lyst,count
def translate(word,dictionary,count):
i = 0
while i != count:
if word == dictionary[i]:
return dictionary[i+1]
i = i+1
else:
return word
i = i+1
return 0
def makeMessage(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst2 = []
string = s.readtoken()
count = 0
while (string != ""):
lyst2.append(string)
string = s.readtoken()
count = count + 1
return lyst2,count
Does anyone know whats going on here? I've looked through several times and i dont know why readString is throwing this error... Its probably something stupid i missed
chr(0x2018) will work if you use Python 3.
You have code that's written for Python 3 but you run it with Python 2. In Python 2 chr will give you a one character string in the ASCII range. This is an 8-bit string, so the maximum parameter value for chris 255. In Python 3 you'll get a unicode character and unicode code points can go up to much higher values.
The issue is that the character you're converting using chr isn't within the range accepted (range(256)). The value 0x2018 in decimal is 8216.
Check out unichr, and also see chr.
I'm running some python code (pasted in) from the console, and getting an unexpected result. Here's what the code looks like:
parentfound = False
structfound = False
instruct = False
wordlist = []
fileHandle = open('cont.h')
for line in fileHandle:
if line is "":
print "skipping blank line"
continue
if "}" in line:
instruct = False
index = line.index("}")
wordlist.append(word)
pass
try:
print wordlist
except Exception as e:
print str(e)
After the for loop, I'd like to print the wordlist. No matter what I do, I can't include anything outside the for loop. Here's the error I receive:
... if "}" in line:
... instruct = False
... index = line.index("}")
... wordlist.append(word)
... pass
... try:
File "<stdin>", line 10
try:
^
SyntaxError: invalid syntax
It occurs whether I type the code by hand into the terminal or if I paste it in. I'd appreciate any help you can offer. Thank you!
The ... prompt in the REPL means that it still hasn't finished the previous block. You will need to press Enter on an empty line to terminate it first.