简体   繁体   English

将文本文件转换为列表并使用索引获取它:

[英]Converting text file to list and getting at it using indexes:

Can anyone tell me why this doesn't work (Python 3) and what I need to do to fix it. 任何人都可以告诉我为什么这不起作用(Python 3)以及我需要做些什么来解决它。 Code and error message below: 代码和错误消息如下:

def verifylogin():

fin=open("moosebook.txt","r")
data=fin.readlines()
line=data

allData = []
for ln in line.split(')('):
    allData.append( ln.lstrip('(').rstrip(')').replace("'", '').replace(' ', '').split(',') )

for data in allData:
    print (data[0]) # print user
print (data[5]) # print profession

output error message: 输出错误信息:

line 30, in verifylogin
for ln in line.split(')('):

AttributeError: 'list' object has no attribute 'split' AttributeError:'list'对象没有属性'split'

The data in the text file is: 文本文件中的数据是:

('CoderBlogJ', 'ggs123', 'J', 'Bloggs', 'Male', 'Coder')('DoctorSmitD', 'ith123', 'D', 'Smith', 'Male', 'Doctor')('teacherminaR', 'neb123', 'R', 'minajneb', 'female', 'teacher')('WriterGardK', 'ens123', 'K', 'Gardens', 'Male', 'Writer')('', '123', '', '', '', '')('', '123', '', '', '', '')('', '123', '', '', '', '')

I want data[0] and data[5] etc to print out the relevant field in the list. 我希望data [0]和data [5]等打印出列表中的相关字段。

Thank you very much for the answer: My final quest however, is to get the username and password to work and because I can't translate it, I can't quite get it to work .... 非常感谢您的回答:我最后的任务是获取用户名和密码,因为我无法翻译它,我无法让它工作....

def verifylogin():
    with open("moosebook.txt") as f:
        data = literal_eval(f.read().replace(")", "),"))
    for user, pw,_,sur,_, job in data: 
        if user:
               print("{}  is a {}".format(user, pw))

     flag=0
for counter in range(0,len(data)):
    if textlogin.get()==data[counter] and textpassword.get()==data[counter+1]:
        flag=flag+1

if flag>0:
            welcome=Label(myGui,text="Access Granted. Loading Profile ....")
            welcome.pack()
else:
                denied=Label(myGui,text="Access Denied")
                denied.pack() 

Your error as stated already is because line is a reference to data which is a list, if each tuple is on a separate line in your file you can use ast.literal_eval to parse the data and just index the tuples to get the dat you want: 您已经说明的错误是因为line是对数据的引用,如果每个元组位于文件的单独一行,您可以使用ast.literal_eval来解析数据,只需索引元组以获取所需的数据:

from ast import literal_eval
def verifylogin():

    with open("test.csv") as f:
        for line in f:
            print(literal_eval(line))
verifylogin()

Output: 输出:

('CoderBlogJ', 'ggs123', 'J', 'Bloggs', 'Male', 'Coder')
('DoctorSmitD', 'ith123', 'D', 'Smith', 'Male', 'Doctor')
('teacherminaR', 'neb123', 'R', 'minajneb', 'female', 'teacher')
('WriterGardK', 'ens123', 'K', 'Gardens', 'Male', 'Writer')
('', '123', '', '', '', '')
('', '123', '', '', '', '')
('', '123', '', '', '', '')

If you have it all in a single line you can str.replace putting a trailing comma after each ) , that will wrap all the tuples in a tuple so ast can parse the file content correctly: 如果你拥有这一切在一个单一的线,你可以str.replace把一个结尾逗号后每个) ,这将包装所有元组的元组这样的AST可以正确地分析文件内容:

def verifylogin():
    with open("test.csv") as f:
        data = literal_eval(f.read().replace(")", "),"))
        for t in data:
            print(t)


verifylogin()

Output will be the same as previously. 输出将与以前相同。

If you are using python3 we can use extended iterable unpacking to get the data we want, ignoring the data with no user with an if check: 如果您使用的是python3,我们可以使用扩展的可迭代解包来获取我们想要的数据,忽略没有用户进行if检查的数据:

from ast import literal_eval

def verifylogin():
    with open("test.csv") as f:
        data = literal_eval(f.read().replace(")", "),"))
        for user, *rest, job in data: # python2 ->  for user, _,_,_,_, job in data:
            if user:
                   print("{}  is a {}".format(user, job))

Output: 输出:

CoderBlogJ  is a Coder
DoctorSmitD  is a Doctor
teacherminaR  is a teacher
WriterGardK  is a Writer

You can get whatever info you want, all the data is unpacked in the loop: 您可以获得所需的任何信息,所有数据都在循环中解压缩:

def verifylogin():
    with open("test.csv") as f:
        data = literal_eval(f.read().replace(")", "),"))
        for user, pw, _, _ , _, job in data:
            if user:
                print("Details for user: {}\nPassword: {}\nJob: {}\n".format(user, pw, job))

Output: 输出:

Details for user: DoctorSmitD
Password: ith123
Job: Doctor

Details for user: teacherminaR
Password: neb123
Job: teacher

Details for user: WriterGardK
Password: ens123
Job: Writer

file.readlines() returns a list of lines in. file.readlines()返回一个行列表。

you did:- 你做了: -

data = fin.readlines()

then data is a list not string 那么data就是list而不是string

line = data

line is a list too, and list don't have split method. line也是一个listlist没有split方法。

Try type() function. 尝试type()函数。

 type(data.readlines())
 list

With the format of the data you give (one line with multiple tuples), and keeping your code, try the following. 使用您提供的数据格式(一行包含多个元组),并保留您的代码,请尝试以下操作。

def verifylogin():
    fin = open("moosebook.txt", "r")
    data = fin.readlines()

    allData = []
    for line in data:
            for ln in line.split(')('):
                allData.append(ln.lstrip('(').rstrip(')').replace("'", '').replace(' ', '').split(','))

    for data in allData:
        print(data[0])  # print user
        print(data[5])  # print profession

verifylogin()

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

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