error:'builtin_function_or_method' object is not iterable - python-3.x

In some other tutorial the following python code for finding words from a json file which worked for them. but, not for me.
would you please help me to get rid of this error.
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def translate(word):
word = word.lower
if word in data:
return data[word]
elif len(get_close_matches(word, data.keys())) > 0:
yn=input ("did you mean %s instead? Enter Y if yes and N if no" % get_close_matches(word, data.keys())[0])
if yn == "Y":
return data[get_close_matches(word, data.keys())[0]]
elif yn == "N":
return("the word doesn't exist")
else:
print("we don't understand your entry")
else:
return("the word does't exist please crosscheck it")
word = input("enter a word: ")
output = translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)
This is the error I got:
Traceback (most recent call last):
File "pracjson.py", line 23, in <module>
output = translate(word)
File "pracjson.py", line 10, in translate
elif len(get_close_matches(word, data.keys())) > 0:
File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 723, in get_close_matches
s.set_seq2(word)
File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 279, in set_seq2
self.__chain_b()
File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 311, in __chain_b
for i, elt in enumerate(b):
TypeError: 'builtin_function_or_method' object is not iterable

Your error is in this line:
word = word.lower
.lower is a method, so it should be:
word = word.lower()
https://docs.python.org/3/library/stdtypes.html?highlight=lower#str.lower

I'm not familiar with get_close_matches. But according to the docs: https://docs.python.org/2/library/difflib.html, it seems like it needs a list (iterable object).
data.keys() returns a dictionary. Try converting that to a list first.
elif len(get_close_matches(word, list(data.keys()))) > 0:

Related

Why is my python 3 EAN query not working?

today I tried to program a EAN query with an EAN database.
I tried to put the request into a json but every time I get an error.
If the query was succesful, you get the data in an MIME-Typ text/plain text format.
What can I do?
Here is my code:
import json
import requests
userid = "&queryid=400000000"
base_url = "http://opengtindb.org/?ean="
query = "&cmd=query"
while True:
print("Welcome to the EAN Database!")
print()
print("1: Search for API")
print("2: Exit")
choice = input("> ")
if choice == "2":
break
if choice == "1":
print("Enter the EAN Number")
print()
ean = input("> ")
ean_call = base_url + ean + query + userid
request = requests.get(ean_call)
print(request.raw)
print(request)
data = request.json()
print(data)
data = data['body']
print(ean)
print(data)
print(ean_call)
Here is the error:
Traceback (most recent call last):
File "/Users/leon/PycharmProjects/ean_api.py", line 28, in <module>
data = request.json()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)

Python - comparing imported values

I would like to import the list from the file, read it line by line (already works). Each line containing a string representing a list.
I have to execute couple of tasks on it, however I got twisted and I dont know why below doesn't work. It gives me the following error :
ErrorCode:
Traceback (most recent call last):
File "main.py", line 8, in <module>
if len(n) != len(str(n + 1)):
TypeError: must be str, not int
f = open('listy.txt', 'r')
content = f.read().split('\n')
for n in content:
n.split(',')
## checking lengh
if len(n) != len(str(n + 1)):
print('Different lengh')
else:
print('All fine.')
Change
n.split(',')
if len(n) != len(str(n + 1)):
to:
n = n.split(',')
len(n[0]) != len(n[1]):
and don't forget to close your file with a f.close()
Better even, use with, example:
with open('listy.txt', 'r') as f:
content = f.read().split('\n')
you do not need a close() method when using with

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)

I/O operation closed on file in python

I have to write a program that prompts the user to enter six test names and their scores and writes them to a text file named tests.txt. You must use a loop. Each input should be written to its own line in the file. The program should generate a confirmation message when done. When I run my program it works but then I get an error at the end saying:
Traceback (most recent call last):
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 34, in <module>
main()
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 18, in main
test_scores.write(name + '\n')
ValueError: I/O operation on closed file.
I am not sure what I am doing wrong, any help would be appreciated.
Here is my code:
def main():
test_scores = open('tests.txt', 'w')
print('Entering six tests and scores')
for count in range(6):
name = input('Enter a test name')
score = int(input('Enter % score on this test'))
while name != '':
test_scores.write(name + '\n')
test_scores.write(str(score) + '\n')
test_scores.close()
print('File was created successfully')
main()
Here's what I did. Get rid of that 2nd while loop, and move the close file out of the for loop because you are closing the file in the loop which is giving you the error: (some of my variable names are different than yours so look out for that)
test_scores = open('tests.txt','w')#open txt file
print('Entering six tests and scores')
for count in range(6):#for loop to ask the user 6 times
name = input('Enter a test name: ')
testscore = int(input('Enter % score on this test: '))
for count2 in range(1):
test_scores.write(str(name) + '\n')
test_scores.write(str(testscore) + '\n')
test_scores.close()#close the txt file
print('File was created successfully!')
the block while:
while name != '':
...
This is an infinity loop if your "name" != '', so in first loop the file closed and second loop you get an error

Python: How (can) I store a "return" or "break" in a dictionary?

select = input("Enter what you would like to do (enter 'x' to exit): ")
functions = {"c": calculator, "a": addsubtract, "s": squareroot,
"p": power, "n": arrange, "f": factorial} # storing break or return result in "Invalid Syntax" in the dictionary
#currently I'm doing this:
if select != "x":
functions[select]()
else:
return
I'm trying to minimize code and have been able to do so by storing functions in a dictionary; I'd like to know if there was a workaround/similar way of doing this in case it's not possible using a dictionary.
You can't:
def r():
return 1
def print_hello():
print("HelloWorld")
l = [print_hello, print_hello, print_hello, r, None]
if __name__ == '__main__':
for i in range(10):
print(i, end='')
l[i]()
$ python3 test.py
> 0HelloWorld
> 1HelloWorld
> 2HelloWorld
> 34Traceback (most recent call last):
> File "test.py", line 14, in <module>
> l[i]()
> TypeError: 'NoneType' object is not callable
And it is not a good idea to store functions in a dictionary:
https://www.python.org/dev/peps/pep-0020/
Flat is better than nested.

Resources