I would like to print a sentence where 2 words change based on some conditions in a dictionary.
If the noun ends with the letter a, then the article having any "any" key with feminine and singular value is used in the sentence. BASICALLY I want to search for any "feminine" and "singular" in all keys. Once the key that has "female" and "singular" is found, then the key "la" is returned
article = {
"il" : {
"gender" : "male",
"unit" : "singular"
},
"la" : {
"gender" : "female",
"unit" : "singular"
},
"le" : {
"gender" : "female",
"unit" : "plural"
},
}
noun = { "torta" : { "genere" : "female", "unità" : "singular" } }
if noun["noun"].endswith('a'):
article is ['gender'] == ['female'] and ['unit'] == ['singular']
text = (f"{''.join(article)} {noun} {è buona}")
print(text)
CodePudding user response:
Some of the strings were in Spanish, and some were in English, which caused issues with matching up the subject and the article. There were also soe minor errors with the original code (e.g. passing a dictionary into an f-string). Correcting for these errors, we get the output (down to capitalization) by looping over article_words.items():
#article
article_words = {
"il" : {
"gender" : "male",
"unit" : "singular"
},
"la" : {
"gender" : "female",
"unit" : "singular"
},
"le" : {
"gender" : "female",
"unit" : "plural"
},
}
#noun
nouns = {
"torta" : {
"gender" : "female",
"unit" : "singular"
}
}
subject = "torta"
if subject.endswith('a'):
article = ""
for key, value in article_words.items():
if nouns[subject] == value:
article = key
break
text = f"{article} {subject} è buona"
print(text)
To get rid of the noun dictionary, you could do the following (see comments for discussion):
endings = {
"a" : {
"gender" : "female",
"unit" : "singular"
}
}
subject = "torta"
ending = None
for key, value in endings.items():
if subject.endswith(key):
ending = key
break
if ending:
article = ""
for key, value in article_words.items():
if endings[ending] == value:
article = key
break
text = f"{article} {subject} è buona"
print(text)
CodePudding user response:
If you restructure article dictionary like:
article = { 'female': { 'singular': 'la', 'plural': 'le' },
'male': { 'singular': 'il' }}
You can use it like this:
word = "torta"
if word.endswith('a'):
article_ = article['female']['singular']
print(f"{article_} {word} e buena")
If you want to use the noun dictionary you can use:
article_ = article[nount[word]['gender']][noun[word]['unita']]
To use article_words as is:
article = next(filter(lambda x: article_words[x]['gender'] == 'female' and
article_words[x]['unit'] == 'singular', article_words.keys()))
will give you the article 'la'
