Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python gender-guesser not able to evaluate gender names

I have a text file with a list of names:

Aaron
Abren
Adrian
Albert

When I run the following code:

import gender_guesser.detector as gender

d = gender.Detector()

file1 = open('names.txt','r')

count = 0

while True:
    count += 1
    line = file1.readline()
    guess = d.get_gender(line)
    print(line)
    print(guess)
    if not line:
        break
print(count)

I get the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Aaron

unknown

Abren

unknown

Adrian

unknown

Albert

male

unknown

5

It looks like it is only able to evaluate the last name in the file (Albert), and I think it has to do with how it parses through the file. If I add a line break after Albert, it no longer detects Albert as male.

Any thoughts?

>Solution :

It looks like you have an issue with the line terminators. The library doesn’t expect those.

Here’s a working code snippet:

import gender_guesser.detector as gender

d = gender.Detector()
with open('names.txt') as fin:
    for line in fin.readlines():
        name = line.strip()
        print(d.get_gender(name))

The main fix is adding line.strip().

Using with is just a best practice you should follow, but doesn’t change the functionality.

The output is:

male
unknown
male
male
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading