0

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:

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?

Daniel Trugman
  • 8,186
  • 20
  • 41
  • 6
    Try stripping the newlines. [How to read a file without newlines?](https://stackoverflow.com/q/12330522) – 001 May 20 '22 at 18:18

1 Answers1

1

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
Daniel Trugman
  • 8,186
  • 20
  • 41