python - How can I get my returned class of specific strings of a txt file added to a list? -



python - How can I get my returned class of specific strings of a txt file added to a list? -

def gettopnames(state, gender, startyear, endyear): """ top names. :param state (str): state, e.g. 'ny' :param gender (str): gender, e.g. 'f' :param startyear (int): starting year, e.g. 1969 :param endyear (int): ending year, e.g. 2010 :return: list of top name objects :rtype: list """ filename = 'data/' + state + '.txt' = startyear file = open(filename) lst = list() open(filename) f: line in f: fields = line.strip().split(",") print(fields) if fields[1] == gender , fields[2] == i: lst.append(createname( fields[3], fields[1], int(fields[2]), fields[0], int(fields[4]))) = +1 if == endyear: break if line == "": break print(lst) homecoming lst def createname(name, gender, year, state, occurrences): """ initialize , homecoming new name object. :param fields (list of str): list of strings represent 1 line in file, [state, gender, year, name, occurrences], e.g. ['ak', 'm', '2004', 'justin', '23'] :return: new name object :rtype: name """ homecoming name(name, gender, year, state, occurrences)

not sure why can't name class added list.

you reading strings file trying compare part of string integer:

if fields[1] == gender , fields[2] == i:

here i integer, fields[2] string. they'll never equal. convert info integer first:

if fields[1] == gender , int(fields[2]) == i:

if info comma-separated, rather split manually, consider using csv module:

with open(filename, 'r', newline='') f: reader = csv.reader(f) fields in reader:

python python-3.x

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -