Domanda

This is the start of a solution for Project Euler Problem 22. I have a sample version of their text file from which I am trying to generate names one name at a time. This is a link to the documentation on string methods. I have written the following code for the task:

def name_gen():
    with open('C:/python/namessample.txt') as nameFile:
        nameGenerator = (i.strip('"').split(sep='","') for i in nameFile)
        for name in nameGenerator:
            yield type(name), type(nameGenerator), type(nameFile), name

for i in name_gen():
    print(i)

This is the code output:

(<class 'list'>, <class 'generator'>, <class '_io.TextIOWrapper'>, ['DOUGLASS', 'CORDELL', 'OSWALDO', 'ELLSWORTH', 'VIRGILIO', 'TONEY', 'NATHANAEL', 'DEL', 'BENEDICT', 'MOSE', 'JOHNSON', 'ISREAL', 'GARRET', 'FAUSTO', 'ASA', 'ARLEN', 'ZACK', 'WARNER', 'MODESTO', 'FRANCESCO', 'MANUAL', 'GAYLORD', 'GASTON', 'FILIBERTO', 'DEANGELO', 'MICHALE', 'GRANVILLE', 'WES', 'MALIK', 'ZACKARY', 'TUAN', 'ELDRIDGE', 'CRISTOPHER', 'CORTEZ', 'ANTIONE', 'MALCOM', 'LONG', 'KOREY', 'JOSPEH', 'COLTON', 'WAYLON', 'VON', 'HOSEA', 'SHAD', 'SANTO', 'RUDOLF', 'ROLF', 'REY', 'RENALDO', 'MARCELLUS', 'LUCIUS', 'KRISTOFER', 'BOYCE', 'BENTON', 'HAYDEN', 'HARLAND', 'ARNOLDO', 'RUEBEN', 'LEANDRO', 'KRAIG', 'JERRELL', 'JEROMY', 'HOBERT', 'CEDRICK', 'ARLIE', 'WINFORD', 'WALLY', 'LUIGI', 'KENETH', 'JACINTO', 'GRAIG', 'FRANKLYN', 'EDMUNDO', 'SID', 'PORTER', 'LEIF', 'JERAMY', 'BUCK', 'WILLIAN', 'VINCENZO', 'SHON', 'LYNWOOD', 'JERE', 'HAI', 'ELDEN', 'DORSEY', 'DARELL', 'BRODERICK', 'ALONSO'])

The type for nameFile and nameGenerator seem to be correct, but name should ideally be one string at a time, not a list of strings. I would guess that the reason why name is a list is because .split returns a list, however I could not figure out a different way to separate the names in the file. Also I used .strip to remove the leading and trailing quotes.

È stato utile?

Soluzione

The file contains one line, so there is no need to loop over the file, really. Just loop over the split list:

def name_gen():
    with open('C:/python/namessample.txt') as nameFile:
        for name in nameFile.read().split(','):
            yield name.strip('"')

or just return the whole list; you've read it into memory already anyway:

def name_gen():
    with open('C:/python/namessample.txt') as nameFile:
        return [name.strip('"') for name in nameFile.read().split(',')]

If you did have multiple lines with each line containing multiple names, you could nest loops:

def name_gen():
    with open('C:/python/namessample.txt') as nameFile:
        for line in nameFile:
            for name in line.rstrip('\n').split(','):
                yield name.strip('"')
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top