0
$\begingroup$

I want to answer this question: "How many sentences contain named entities given a doc?" and I have this piece of code as solution

nb = 0

for sent in list(doc.sents):
    if sent.ents:
        nb = nb+1

print(nb)

But I am a little confused about how the if-statement work; consider that the actual sentence(sent) does not have any entities(ents), so sent.ents will return an empty list I suppose and I can't understand why an empty list is considered as a false statement because the program when executed does not enter the if.

$\endgroup$
1
$\begingroup$

You could just test whether the tuples entities has any elements:

for sent in list(doc.sents):
    if len(sent.ents) > 0:
        nb = nb+1

Edit: For the purpose of evaluating boolean expressions (as in case of if statements), empty lists are evaluated as false, even though they don't explicitly equal False. Expanding your example with some print statements:

nb = 0
spacy_nlp = spacy.load("de_core_news_md")
text = "Nichts. Auch nichts."
doc = spacy_nlp(text)
for sent in list(doc.sents):
    print("type of ents: " + str(type(sent.ents)) + " with " + str(len(sent.ents)) + " elements.")
    if sent.ents:
        nb = nb+1

print(nb)

Results in:

type of ents: <class 'list'> with 0 elements.
type of ents: <class 'list'> with 0 elements.
0
| improve this answer | |
$\endgroup$
  • $\begingroup$ I appreciate your help, but this is not what I asked. I am wondering if an empty list returned by sent.ents is considered as false. $\endgroup$ – Ghassen Ben Hamida Apr 9 at 12:34
  • $\begingroup$ Valid point. I extended the answer. Hope this helps. $\endgroup$ – rolando Apr 10 at 10:41
  • $\begingroup$ yes this helped. $\endgroup$ – Ghassen Ben Hamida Apr 10 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.