简体   繁体   English

输入验证并将元组列表转换为 txt 文件

[英]Input validation and converting list of tuples to txt file

Im trying to convert a list of tuples to a txt file and do a input validation for two inputs.我试图将元组列表转换为 txt 文件并对两个输入进行输入验证。 BTW, Im trying to do it without and CSV modules.顺便说一句,我试图在没有 CSV 模块的情况下做到这一点。 I got this list of tuples:我得到了这个元组列表:

list1 = [(16, 'Peter' , 2005) , (21, 'Philip', 2000) , (10, 'Kate', 2011)]

and I want to convert it to a txt file which looks like that:我想将它转换为一个看起来像这样的 txt 文件:

Age      Name     YOB
16       Peter    2005
21       Philip   2000
10       Kate     2011

and I need to do an Input validation for the confirm that the first input is a list and the second input is a string.我需要进行输入验证,以确认第一个输入是一个列表,第二个输入是一个字符串。 the file lines should be seperated with tabs.文件行应该用制表符分隔。

def my_func(list1,new_file):
   header = "Age, Name, YOB"
   if isinstance(list1, list):
      for i in list1:
        if isinstance(list1[i], str):
            with open("Age_file.txt", "w") as output:
                output.write(header + "\n")
                output.close()
                with open("Age_file.txt", "w") as output:
                    for i in output:
                        output.write(str(i) + "\n")
        else:
            "Second input must be a str."
else:
    "First input must be a list."

but I get this this typeerror:但我得到这个类型错误:

'''
if isinstance(list1[i], str):
TypeError: list indices must be integers or slices, not tuple
'''

Appreciate any kind of help, Thanks!感谢任何形式的帮助,谢谢!

The issue here is that i in your second for loop is a tuple as described in your traceback.这里的问题是您的第二个for循环中的i是您的回溯中描述的tuple You are in essence trying to do the following which errors out:您本质上是在尝试执行以下错误:

list1[(16, 'Peter' , 2005)]

It sounds like you want to make sure that the second item of each tuple is a str , in which case your code should look like this.听起来您想确保每个元组的第二项是str ,在这种情况下,您的代码应该如下所示。 I also modified it so that you only open the file once , not on every iteration and went ahead and used the new_file param which you seem to not be using at all.我还对其进行了修改,以便您只打开文件一次,而不是在每次迭代时继续使用您似乎根本没有使用的new_file参数。

def my_func(list1, new_file):
    if not isinstance(list1, list):
        raise ValueError("First argument must be a list!")
    header = "Age, Name, YOB"
    with open(new_file, "w") as output:
        output.write(header + "\n")
        for line in list1:
            if not isinstance(line[1], str):
                raise ValueError("Second item in each tuple must be a str!")
            
            vals = ",".join(str(i) for i in line)
            output.write(vals + "\n")

Did you try to do three seperate lists isntead of tuples?您是否尝试过创建三个单独的列表而不是元组? then you have one list of strings only and two lists of numbers only... then you can put:那么你只有一个字符串列表和两个数字列表......然后你可以输入:

list1 = [16, 21, 10]
list2 = ['Peter', 'Philipp', 'Kate']
list3 = [2005, 2000, 2010]
listfull = list(zip(list1, list2, list3))

and then you can make a dataframe out of these lists:然后你可以从这些列表中制作一个 dataframe :

df = pd.DataFrame(listfull, columns =['Age', 'Name', 'YOB'])

and then you can safe this as a text or csv file... not sure if that helps..然后您可以将其保存为文本或 csv 文件...不确定是否有帮助..

df.to_csv('df.csv')

Why your code fails is mentioned in the comment below:下面的评论中提到了您的代码失败的原因:

list1 = [(16, 'Peter' , 2005) , (21, 'Philip', 2000) , (10, 'Kate', 2011)]
# list1 is a list of tuples here

def my_func(list1,new_file):
    #assuming we are getting same list1 defined above list1 is still list of tuples
    header = "Age, Name, YOB"
    if isinstance(list1, list):
        for i in list1:
            # i should be tuples like (16, 'Peter' , 2005)
            if isinstance(list1[i], str): # error thrown because i is tuple
                with open("Age_file.txt", "w") as output:
                    output.write(header + "\n")
                    output.close()
                    with open("Age_file.txt", "w") as output:
                        for i in output:
                            output.write(str(i) + "\n")
            else:
                "Second input must be a str."
    else:
        "First input must be a list."
        

You can try the below code:你可以试试下面的代码:

list1 = [(16, 'Peter' , 2005) , (21, 'Philip', 2000) , (10, 'Kate', 2011)]
# list1 is a list of tuples here


def my_func(list1,new_file):
    if not isinstance(list1, list):
        raise Exception("list1 must be a list") # exception thrown in case list1 is not a list
    if not isinstance(new_file, str):
        raise Exception("new_file must be a str") # exception thrown in case new file is not a str.
        # However in your code it is not clear what is the purpose of argument new_file
    result = "Age\tName\tYOB\n" # \t for tab. tab is better than space is it somewhat maintains indentation of the columns
    for list2 in list1:
        result += "\t".join([str(x) for x in list2]) + "\n"
        # list comprehension used to convert all item in tuple list2 to strings
    with open("Age_file.txt", "w") as output:
        output.write(result.strip())


my_func(list1, "test")

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

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