繁体   English   中英

从输入文件创建名称列表

[英]Creating a List of Names from an Input File

我疯狂地尝试找出如何摆脱错误“ str has no attribute append”。 我需要将人的名字从输入文件添加到name_list。

输入文件中的典型行将显示为:

塔梅卡·哈里斯3/4/17

这是我到目前为止的代码:

def process_input(file1, any_dict, any_set):

    #open input file
    customer_input_file = open(file1, 'r')


    #initialize a list to store info by line
    line_list = []

    #Create a name counter
    index = 0

    #read file line by line
    for line in customer_input_file:
        #split the line
        line_list = line.split()
        #slice the list to make a list with only names and no dates
        name_list = line_list[-1]
        #create a variable for first name from list
        fname = name_list[0].title()
        #create a last name variable from list
        lname = name_list[1].title()
        #add the two name variables together as a new list
        input_name = [fname + ' ' + lname]


        #add names to name list
        name_list.append(input_name)

        #add names to name list
        any_set.add(name_list[index])

        #count the times a name repeats in the name list
        any_dict[input_name] = name_list.count(input_name)


        #add 1 to index
        index += 1


    #Close input file
    customer_input_file.close
# slice the list to make a list with only names and no dates
name_list = line_list[-1]

上面的代码返回列表中的最后一个项目,它是一个字符串,这就是为什么name_list.append(input_name)引发错误的原因。

您需要排除最后一项:

name_list = line_list[:-1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM