Reputation: 155
I am writing a simple dictionary program using Python 3 and kivy.
class MainScreen(Screen):
def define(self, w):
with open('data.json') as dict_file:
data = json.load(dict_file)
for number, meaning in enumerate(data[w]):
return str(number + 1) + ') ' + meaning
def show_meaning(self, w):
with open('data.json') as dict_file:
data = json.load(dict_file)
w = w.casefold()
if w in data.keys():
self.ids.meaning.text = f"{self.define(w)}"
print("Meaning printed")
elif len(get_close_matches(w, data.keys(), cutoff=0.8)) > 0:
d = enumerate(get_close_matches(w, data.keys(), cutoff=0.7))
self.ids.meaning.text = f"Did you mean this/any of these?\n{[(number + 1, name) for number, name in d]}"
time.sleep(3)
elif w == '' or w == ' ' or w == ' ' or w == ' ' or w == ' ' or w == ' ' or w == ' ':
self.ids.meaning.text = "Please enter something"
else:
self.ids.meaning.text = "Double check the word or try another word."
This is the main portion of the program. The dictionary "data" has multiple keys each having a value which is a list containing single or multiple definitions of the word. If a word has more than one meaning, a list is returned and I want to return each meaning(item of the list) on a different line. But if a for loop is used, it returns only the first meaning(item of the list) and breaks, thus not returning the second or further outputs. How can I overcome this problem? Please suggest a solution.
Following is the Kivy code:
<MainScreen>:
GridLayout:
cols: 1
Label:
text: "Dictionary"
font_size: "40sp"
TextInput:
id: word
hint_text: "Enter a word to know its meaning"
ScrollView:
Label:
id: meaning
text: ""
text_size: self.width, None
size_hint_y: None
height: self.texture_size[1]
Button:
text: "Enter"
on_press: root.show_meaning(root.ids.word.text)
size_hint: 0.2, 0.5
pos_hint: {'center_x': 1.5, 'center_y': 0.6}
<RootWidget>:
MainScreen:
name: "main_screen"
Upvotes: 0
Views: 268
Reputation: 39082
Your loop in the define()
method:
for number, meaning in enumerate(data[w]):
return str(number + 1) + ') ' + meaning
does not actually loop, but returns on the first entry in your data
.
Try something like:
defs = []
for number, meaning in enumerate(data[w]):
defs.append(str(number + 1) + ') ' + meaning + '\n')
return ''.join(defs)
Upvotes: 1