尝试打印映射数据但函数没有返回任何内容

Trying to print mapped data but function is returning nothing

import numpy as np
with open("/Users/myname/Downloads/names/yob1880.txt","r") as f:
    text = f.readlines()
for line in text:
    print (line)
def mapper():
    for lines in line:
        data = line.strip().split("\t")
        name, sex, number = data
        print ("{0}\t{1}".format(name, number))

数据集包含以逗号分隔的名称、性别和编号值。数据集取自这里:https://www.ssa.gov/oact/babynames/names.zip

enter image description here

我想,而不是

for lines in line:
        data = line.strip().split("\t")
        name, sex, number = data
        print ("{0}\t{1}".format(name, number))

您实际上应该使用单行(在您的情况下称为 lines 或重新表述您的变量)。

因此,在这里考虑一下:

for line in text:
        data = line.strip().split(',')

你看出区别了吗? linesline?


此外,阅读评论和提供的文件,您应该split(',')

或者更好的是,使用 csv 模块,它带有一个 csv reader。

试试这个:

import numpy as np
import csv

with open("/Users/myname/Downloads/names/yob1880.txt","r") as f:
    csv_file = csv.reader(f)
    def mapper():
        for line in csv_file:
            name, sex, number = line
            print ("{0}\t{1}".format(name, number))
    mapper()

csv 模块帮了大忙。