I am trying to write a code from the following tutorial:
https://www.youtube.com/watch?v=9mAmZIRfJBs&t=197s
In my opinion I completely wrote it the same way, but it still gives an error. Can someone explain to me why Spyder(Python 3.7) does this.
This is my code:
I tried using another input function so raw_input instead of input. I also tried changing my working directory and saving the document
This is my code:
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 14:47:27 2019
#author: johan
"""
import random
restaurantsList = ['boloco', 'clover', 'sweetgreens']
def pickRestaurant():
print(restaurantsList[random.randint(0,2)])
def addRestaurant(name):
restaurantsList.append(name)
def removeRestaurant(name):
restaurantsList.remove(name)
def listRestaurant():
for restaurant in restaurantsList:
print(restaurant)
while True:
print('''
[1] - List restaurant
[2] - Add restaurant
[3] - Remove restaurant
[4] - Pick restaurant
[5] - Exit
''')
selection = raw_input(prompt='Please select an option: ')
if selection == '1':
print('')
listRestaurant()
elif selection == '2':
inName = raw_input(prompt='Type name of the restaurant that you want to add: ')
addRestaurant(inName)
elif selection == '3':
inName = raw_input(prompt='Type name of the restaurant that you want to remove: ')
removeRestaurant(inName)
elif selection == '4':
pickRestaurant()
elif selection == '5':
break
and this is the error
runfile('C:/Users/johan/Desktop/Unie jaar 2/untitled2.py', wdir='C:/Users/johan/Desktop/Unie jaar 2')
Traceback (most recent call last):
File "C:\Users\johan\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-93-2d7193d6cafb>", line 1, in <module>
runfile('C:/Users/johan/Desktop/Unie jaar 2/untitled2.py', wdir='C:/Users/johan/Desktop/Unie jaar 2')
File "C:\Users\johan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
execfile(filename, namespace)
File "C:\Users\johan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/johan/Desktop/Unie jaar 2/untitled2.py", line 35
selection = raw_input(prompt='Please select an option: ')
^
IndentationError: unindent does not match any outer indentation level
The code should give a list of restaurant is 1 is put in. You are able to add a restaurant to the list if 2 is put in. 3 is like to but then you remove. 4 picks a random restaurant from the list. 5 does nothing.
It's imperative that you indent correctly in Python, as such;
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 14:47:27 2019
#author: johan
"""
import random
restaurantsList = ['boloco', 'clover', 'sweetgreens']
def pickRestaurant():
print(restaurantsList[random.randint(0,2)])
def addRestaurant(name):
restaurantsList.append(name)
def removeRestaurant(name):
restaurantsList.remove(name)
def listRestaurant():
for restaurant in restaurantsList:
print(restaurant)
while True:
print('''
[1] - List restaurant
[2] - Add restaurant
[3] - Remove restaurant
[4] - Pick restaurant
[5] - Exit
''')
selection = input('Please select an option: ')
if selection == '1':
print('')
listRestaurant()
elif selection == '2':
inName = input('Type name of the restaurant that you want to add: ')
addRestaurant(inName)
elif selection == '3':
inName = input('Type name of the restaurant that you want to remove: ')
removeRestaurant(inName)
elif selection == '4':
pickRestaurant()
elif selection == '5':
break
Python is indentation sensitive, and when creating a function or any statements you need to indent any code inside that function or you will get the error you have above.
Additional note: You're using print() which is python2 and raw_input which is python3, so I've assumed Python3 and changed the raw_input() for input().
You have 4 spaces before print statement within while loop, but all other lines in that loop have 3 spaces indent only, starting from selection = raw_input...
You should add a space at the start for every line starting from selection = raw_input... and below.
Related
I'm trying to open a csv file for my python book project and this error keeps popping up
File "c:\Users\MSFT Surface Pro 3\Documents\Programming\Python\Python AIO\Code.py", line 13, in <module> birthYear = int(row[1] or 0) ValueError: invalid literal for int() with base 10: ' 1/11/2011'
and this is super annoying, help me please!
Looks like line 13 in in Code.py is birthYear = int(row[1] or 0), but probably should be something like birthYear = row[1] or "".
So I'm trying to learn some python3 with some simple code as stated below. The point of the code is to have a loop that runs until one of the files exists and contains data. For some reason i'm getting an error running this, saying that the variable has an invalid syntax just as if numbers in variables are illegal (which they arent?):
$ python3 test.py
File "test.py", line 14
While file1==False and file2==False and file3==False:
^
SyntaxError: invalid syntax
Code:
import os
filePath1 = '/some/path'
filePath2 = '/some/path'
filePath3 = '/some/path'
file1 = False
file2 = False
file3 = False
While file1==False and file2==False and file3==False:
if os.path.exists(filePath1):
with open(filePath1,'r') as f:
try:
file1 = f.read()
except:
print("No file data.")
if os.path.exists(filePath2):
with open(filePath2,'r') as f:
try:
file2 = f.read()
except:
print("No file data.")
if os.path.exists(filePath3):
with open(filePath3,'r') as f:
try:
file3 = f.read()
except:
print("No file data.")
I don't understand this because:
>>>file1=False
>>>file2=False
>>>file1==False and file2==False
True
I'd be grateful for any help
invalid syntax is caused by your capitalized While keyword, which python doesn't recognize. Use the reserved keyword while, small letters only.
Student trying to compare two .txt files of string "answers" from a multiple choice test a,c,d,b, etc. I've found some information on different parts of the problems I'm having and found a possible way to get the comparisons I want, but the guide was meant for in script strings and not pulling a list from a file.
For the import of the two files and comparing them, I'm basing my code on my textbook and this video here: Video example
I've got the code up and running, but for some reason I'm only getting 0.0% match when I want to a 100.0% match, at least for the two text files I'm using with identical answer lists.
import difflib
answer_sheet = "TestAnswerList.txt"
student_sheet = "StudentAnswerList.txt"
ans_list = open(answer_sheet).readlines()
stu_list = open(student_sheet).readlines()
sequence = difflib.SequenceMatcher(isjunk=None, a=ans_list, b=stu_list)
check_list = sequence.ratio()*100
check_list = round(check_list,1)
print(str(check_list) + "% match")
if check_list == 100:
print('This grade is Plus Ultra!')
elif check_list >= 75:
print('Good job, you pass!')
else:
print('Please study harder for your next test.')
# not the crux of my issue, but will accept advice all the same
answer_sheet.close
student_sheet.close
If I add in the close statement at the end for both of the text files, then I receive this error:
Traceback (most recent call last): File
"c:/Users/jaret/Documents/Ashford U/CPT 200/Python Code/Wk 5 Int Assg
- Tester code.py", line 18, in
answer_sheet.close AttributeError: 'str' object has no attribute 'close'
I had to re-look at how my files were being opened and realized that the syntax was for Python 2 not 3. I chose to go w/ basic open and later close to reduce any potential errors on my novice part.
import difflib
f1 = open('TestAnswerList.txt')
tst_ans = f1.readlines()
f2 = open('StudentAnswerList.txt')
stu_ans = f2.readlines()
sequence = difflib.SequenceMatcher(isjunk=None, a=stu_ans, b=tst_ans)
check_list = sequence.ratio()*100
check_list = round(check_list,1)
print(str(check_list) + "% match") # Percentage correct
if check_list == 100:
print('This grade is Plus Ultra!')
elif check_list >= 75:
print('Good job, you pass!')
else:
print('Please study harder for your next test.')
# Visual Answer match-up
print('Test Answers: ', tst_ans)
print('Student Answers:', stu_ans)
f1.close()
f2.close()
I'm getting this error when I try to import users
NB:
the module works fine: I can import users using odoo 10 and postgres 9.3 ubuntu 14
but here I'm using postgres 9.5 odoo 10 ubuntu 16
File "/home/belazar/Documents/addons_odoo10/hr_biometric_machine/models/biometric_machine.py", line 113, in create_user
'biometric_device': self.id, }
File "/opt/odoo/odoo/models.py", line 3830, in create
record = self.browse(self._create(old_vals))
File "/opt/odoo/odoo/models.py", line 3925, in _create
cr.execute(query, tuple(u[2] for u in updates if len(u) > 2))
File "/opt/odoo/odoo/sql_db.py", line 154, in wrapper
return f(self, *args, **kwargs)
File "/opt/odoo/odoo/sql_db.py", line 231, in execute
res = self._obj.execute(query, params)
ValueError: A string literal cannot contain NUL (0x00) characters.
the problem is solved by on /opt/odoo/odoo/sql_db.py commenting those lines:
#from tools import parse_version as pv
#if pv(psycopg2.__version__) < pv('2.7'):
# from psycopg2._psycopg import QuotedString
# def adapt_string(adapted):
# """Python implementation of psycopg/psycopg2#459 from v2.7"""
# if '\x00' in adapted:
# raise ValueError("A string literal cannot contain NUL (0x00) characters.")
# return QuotedString(adapted)
#psycopg2.extensions.register_adapter(str, adapt_string)
#psycopg2.extensions.register_adapter(unicode, adapt_string)
I am using python 3.5 on both windows and Linux but get the same error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc1 in position 0: ordinal not in range(128)
The error log is the following:
Reloaded modules: lazylinker_ext
Traceback (most recent call last):
File "<ipython-input-2-d60a2349532e>", line 1, in <module>
runfile('C:/Users/YZC/Google Drive/sunday/data/RA/data_20100101_20150622/w2v_coherence.py', wdir='C:/Users/YZC/Google Drive/sunday/data/RA/data_20100101_20150622')
File "C:\Users\YZC\Anaconda3\lib\site- packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "C:\Users\YZC\Anaconda3\lib\site- packages\spyderlib\widgets\externalshell\sitecustomize.py", line 88, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/YZC/Google Drive/sunday/data/RA/data_20100101_20150622/w2v_coherence.py", line 70, in <module>
model = gensim.models.Word2Vec.load('model_all_no_lemma')
File "C:\Users\YZC\Anaconda3\lib\site-packages\gensim\models\word2vec.py", line 1485, in load
model = super(Word2Vec, cls).load(*args, **kwargs)
File "C:\Users\YZC\Anaconda3\lib\site-packages\gensim\utils.py", line 248, in load
obj = unpickle(fname)
File "C:\Users\YZC\Anaconda3\lib\site-packages\gensim\utils.py", line 912, in unpickle
return _pickle.loads(f.read())
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc1 in position 0: ordinal not in range(128)
1.I checked and found the default decode method is utf-8 by:
import sys
sys.getdefaultencoding()
Out[2]: 'utf-8'
when read the file, I also added .decode('utf-8')
I did add shepang line in the beginning and declare utf-8
so I really dont know why python couldnt read the file. Can anybody help me out?
Here are the code:
# -*- coding: utf-8 -*-
import gensim
import csv
import numpy as np
import math
import string
from nltk.corpus import stopwords, wordnet
from nltk.stem import WordNetLemmatizer
from textblob import TextBlob, Word
class SpeechParser(object):
def __init__(self, filename):
self.filename = filename
self.lemmatize = WordNetLemmatizer().lemmatize
self.cached_stopwords = stopwords.words('english')
def __iter__(self):
with open(self.filename, 'rb', encoding='utf-8') as csvfile:
file_reader = csv.reader(csvfile, delimiter=',', quotechar='|', )
headers = file_reader.next()
for row in file_reader:
parsed_row = self.parse_speech(row[-2])
yield parsed_row
def parse_speech(self, row):
speech_words = row.replace('\r\n', ' ').strip().lower().translate(None, string.punctuation).decode('utf-8', 'ignore')
return speech_words.split()
# -- source: https://github.com/prateekpg2455/U.S-Presidential- Speeches/blob/master/speech.py --
def pos(self, tag):
if tag.startswith('J'):
return wordnet.ADJ
elif tag.startswith('V'):
return wordnet.VERB
elif tag.startswith('N'):
return wordnet.NOUN
elif tag.startswith('R'):
return wordnet.ADV
else:
return ''
if __name__ == '__main__':
# instantiate object
sentences = SpeechParser("sample.csv")
# load an existing model
model = gensim.models.Word2Vec.load('model_all_no_lemma')
print('\n-----------------------------------------------------------')
print('MODEL:\t{0}'.format(model))
vocab = model.vocab
# print log-probability of first 10 sentences
row_count = 0
print('\n------------- Scores for first 10 documents: -------------')
for doc in sentences:
print(sum(model.score(doc))/len(doc))
row_count += 1
if row_count > 10:
break
print('\n-----------------------------------------------------------')
It looks like a bug in Gensim when you try to use a Python 2 pickle file that has non-ASCII chars in it with Python 3.
The unpickle is happening when you call:
model = gensim.models.Word2Vec.load('model_all_no_lemma')
In Python 3, during the unpickle it wants to convert legacy byte strings to (Unicode) strings. The default action is to decode with 'ASCII' in strict mode.
The fix will be dependant on the encoding in your original pickle file and will require you to patch the gensim code.
I'm not familiar with gensim so you will have to try the following two options:
Force UTF-8
Chances are, your non-ASCII data is in UTF-8 format.
Edit C:\Users\YZC\Anaconda3\lib\site-packages\gensim\utils.py
Goto line 912
Change line to read:
return _pickle.loads(f.read(), encoding='utf-8')
Byte mode
Gensim in Python3 may happily work with byte strings:
Edit C:\Users\YZC\Anaconda3\lib\site-packages\gensim\utils.py
Goto line 912
Change line to read:
return _pickle.loads(f.read(), encoding='bytes')