Python: what to fix in the following code to make it run? - python-3.x

I have the following code where i am facing error and i am unable to identify the actual issue here. The code takes a .json file which holds the words and their meanings and finds the exact or nearest matches of the words given as input by the user along with their meanings. The code was running fine until i tried to modify it a little. I wanted to add the matching words where the first word is capital in the following line post which it started throwing exception:
Changed line:
if (word != "") and ((word in data.keys()) or (word.capitalize() in data.keys())):
Code:
import json
import difflib
def searchWord(word):
if (word != "") and ((word in data.keys()) or (word.capitalize() in data.keys())):
return data[word]
else:
closematch = difflib.get_close_matches(word,data.keys())[0]
confirmation = (input(f"\nDid you mean: {closematch} (y/n): ")).lower()
if confirmation == 'y':
return data[closematch]
else:
return 'Word Not Found in Dictionary'
print('Loading Data...\n')
data = json.load(open('data.json'))
print('Data Loaded!\n')
word = (input('Enter word to lookup in dictionary: ')).lower()
meanings = searchWord(word)
if meanings == list:
for meaning in meanings:
print("\n"+meaning)
else:
print(meanings[0])
Error:
Loading Data...
Data Loaded!
Enter word to lookup in dictionary: delhi
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
E:\Learning\Python\AdvancedPython\PythonMegaCourse\DictionaryApp\dictionary.py in <module>()
20 word = (input('Enter word to lookup in dictionary: ')).lower()
21
---> 22 meanings = searchWord(word)
23 if meanings == list:
24 for meaning in meanings:
E:\Learning\Python\AdvancedPython\PythonMegaCourse\DictionaryApp\dictionary.py in searchWord(word)
4 def searchWord(word):
5 if (word != "") and ((word in data.keys()) or (word.capitalize() in data.keys())):
----> 6 return data[word]
7 else:
8 closematch = difflib.get_close_matches(word,data.keys())[0]
KeyError: 'delhi'
The .json file has got a key named Delhi however, the capitalize() doesn't seem to work.

When you are trying to access the word from the dictionary, you are not capitalizing it.
This is not a clean way to handle it but to give you the idea.
if (word != "") and (word in data.keys()):
return data[word]
if (word != "") and (word.capitalize() in data.keys()):
return data[word.capitalize()]

Related

Trouble printing out dictionary.meaning() output using PyDictionary

I'm trying to make a program that will grab a random word from a JSON file and print it and it's definition using PyDictionary. It works occasionally but I think the issue I am having is displaying output from dictionary.meaning(word) when the word has multiple meanings. I get an IndexError when that appears the be the case.
example outputs: expected: tinamidae Noun ['comprising the
tinamous']
unwanted result: unmaterially Error: The Following Error occured: list
index out of range No definition found!
import json
import random
from PyDictionary import PyDictionary
dictionary = PyDictionary()
with open('C:\\Users\\jabes\\Desktop\\words_dictionary.json') as json_file:
words = json.load(json_file)
word = random.choice(list(words.keys()))
print(word)
try:
meanings = dictionary.meaning(word)
if meanings:
for k,v in meanings.items():
print(k, v)
else:
print("No definition found!")
except Exception as error:
print(error)
print("Exiting!")

Error: IndexError: list index out of range

I am new to python and I am getting an error while executing the below piece of code. Would really appreciate if anybody could help me understand it.
About the data: The dataframe is stored in "train" and the column name is "neighborhood". values in "neighborhood" are like "#Queens#jackson heights" or "#Manhattan#uppereast side". So i am trying to split hashtags and then consider only the first word in each row (i.e. Queens & Manhattan $ etc.)
It does print the expected output but with this error:
IndexError Traceback (most recent call last)
<ipython-input-89-b199ce84fe1c> in <module>()
5 for row in train['neighborhood'].str.split('#'):
6 # if more than a value,
----> 7 if len(row[1]) == 5 :
8 # Append a num grade
9 grades.append('1')
IndexError: list index out of range
train = pd.DataFrame(train, columns = ['id','listing_type','floor','latitude','longitude','price','beds','baths','total_rooms','square_feet','pet_details','neighborhood'])
# Create a list to store the data
grades = [ ]
# For each row in the column,
for row in train['neighborhood'].str.split('#'):
# if more than a value,
if row[1] == 'Queens':
# Append a num grade
grades.append('1')
# else, if more than a value,
elif row[1] == 'Manhattan':
# Append a letter grade
grades.append('2')
# else, if more than a value,
elif row[1] == 'Bronx':
# Append a letter grade
grades.append('3')
# else, if more than a value,
elif row[1] == 'Brooklyn':
# Append a letter grade
grades.append('4')
# else, if more than a value,
else:
# Append a fail0ing grade
grades.append('5')

Getting error in list assignment about index?

I recently started to study Python, and as I was trying to run a code from a book (with my modification) I got the error:
IndexError: list assignment index out of range
in : `Names[len(Names)]=name`
I read some questions with this error on web but can't figure it out.
Names=[]
num=0
name=''
while True :
print('Enter the name of person '+str(len(Names)+1) + '(or Enter nothing to stop)')
name=input()
if name == '' :
break
Names[len(Names)]=name
print('the person names are:')
for num in range(len(Names)+1) :
print(' '+Names[num])
Looks like you want to append something to an existing list. Why not use .append()? This won't give you the IndexError.
Names.append(name)
Another same error: You shouldn't write range(len(Names) + 1). range(len(Names)) is enough for you to iterate through the whole list:
for num in range(len(Names)):
print(' '+Names[num])
Another suggestion: You don't need the for loop to print the result, at all. Just use str.join():
print(' '.join(Names))
You can not access out of range index
Ex:
>>> l = [1,2,3]
>>> l = [0,1,2]
>>> l[3] = "New"
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
l[3] = "New"
IndexError: list assignment index out of range
For that, you have to append new data to the list.
>>> l.append("new")
>>> l
[0, 1, 2, 'new']
You can try:
Names=[]
num=0
name=''
while True :
print('Enter the name of person '+str(len(Names)+1) + '(or Enter nothing to stop)')
name=input()
if name == '' :
break
Names.append(name)
print('the person names are:')
for num in range(len(Names)) :
print(' '+Names[num])
just use the append function to insert the new name to the existing list of names.
Syntax:-
if you want to append 'foo' to the list of existing names i.e 'Names',type Names.append('foo').

random.choice displays an error

I am new to stack overflow and I was wondering if anyone could help me with the following question. If you know a similar question that was answered, please point me towards it. thanks:)
This is my code to create a function load_words() that creates a list of 6 letter words from the file "words.txt". I want the random.choice() to pick a random word from the list and save it into word. However, I get the error below.
import random
def load_words(filename, length):
file = open(filename, "r")
words = []
for line in file:
word = line.strip()
if len(word)== length:
words.append(word)
return words
word = random.choice(words)
print (word)
the error I get is:
Traceback (most recent call last):
File "C:\Users\mssuk\Desktop\University\Software Engineering\Assignment\assignment 1 - word guessing game\compute_score.py", line 14, in <module>
word = random.choice(words)
NameError: name 'words' is not defined
It's an indentation error. Indent your return statement by 4 spaces and the code will work.
import random
def load_words(filename, length):
file = open(filename, "r")
words = []
#Assuming there is only one word in a line
for line in file:
word = line.strip().lower()
if len(word) == length:
words.add(word)
file.close()
return words
word = random.choice(load_words(your_filename, your_length)
print(word)

Python 3: Checking for the length and data type. & Error Fix

I am having some problems with my project:
With the code I currently have, I am getting an error:
Traceback (most recent call last):
File "\Username\Folder\Folder2\design2.py", line 13, in <module>
elif numberplate3.isaplha():
AttributeError: 'str' object has no attribute 'isaplha'
Here is the code:
while True:
import time
numberplate1 = str(input("Enter in the first 2 letters of the numberplate"))
if numberplate1.isalpha():
print("Verification 1 Success")
numberplate2 = str(input("Enter in the next 2 chars of the numberplate"))
if numberplate2.isdigit():
print("Verification 2 Success")
numberplate3 = str(input("Enter the last 3 digits of the numberplate"))
if numberplate3.isdigit():
print("Verification 3 Fail")
break
elif numberplate3.isaplha():
print("Verification Passed")
start
elif numberplate2.isalpha():
print("Verification 2 Failed")
break
elif numberplate1.isdigit():
print("Return to the start")
break
start = time.time()
inp = input("Please press enter when car has left monitoring area\n>")
end = time.time()
print("Car took {:.2f} seconds ".format(end-start))
print("Car travelled at {:.2f} m/s. ".format(200/(end-start)))
The program will check the format of a numberplate, but I would also like for it to check for the length too. (It checks to see if it has a letter, number etc, but it needs to check for the length on each check)
If possible, a program that checks for the numberplate format would really help.
Checking for LETTER-LETTER-NUMBER-NUMBER LETTER-LETTER-LETTER (AB12 CDE) If not, I am fine with help on my current program
Thanks
Your first problem is just a typo: You misspelled 'isaplha'; it should be 'isalpha'.
For your other question: You can make your program a whole lot simpler by using a regular expression for matching the number plate, like this:
import re
while True:
numberplate = input("Enter the numberplate: ").lower()
if re.match("[a-z]{2}[0-9]{2}[a-z]{3}", numberplate):
print("Verification Success")
break
else:
print("Verification Failed")
Here, the regular expression "[a-z]{2}[0-9]{2}[a-z]{3}" means "two letters, two digits, three letters".

Resources