繁体   English   中英

无法在循环中使用next()获得下一行

[英]Can't get the next line using next() in a loop (python)

我正在尝试编写一个遍历txt文件的代码,只获取我要打印出来的行。

文本文件应如下所示:

mimi
passwordmimi
mimi johnson
somejob
joji
passwordjoji
jojo
somejob
john
passwordjohn
jonathan
somejob
....

等等。 该文本文件基本上包含用户信息(用于登录)。 我需要打印出每个人的用户名和真实姓名(例如:mimi和mimi johnson)。 我不想打印当前用户的信息(在此示例中:joji)

这是我的代码:

username="joji"

file=open("username.txt","r") 
x=file.readlines()

x=[item.rstrip('\n') for item in x]

x=iter(x)

for line in x:
      if line==username:
              next(x,None)
              next(x,None)
              next(x,None)
      else:
              print line + " username"    ****username should print out. ex:mimi or john
              next(x,None)
              print line +" real name   ****real name should print out. ex: mimi johnson or jonathan

不管出于什么原因,当我运行该程序并打印出第二个****时,它都会打印出两次用户名。 (因此:

mimi username
mimi real name
mimi johnson username
mimi johnson real name
john username
john real name
jonathan username
jonathan real name
....

这是为什么? 它应该打印出来

mimi username
mimi johnson real name
john username
jonathan realname 
...

如果有人可以帮助我,我将非常感激我没有python。 我也愿意接受任何其他建议来做到这一点。

编辑:::我试图进行更改,建议是这样:

新的代码块:

else: 
      print line + "username" 
      line =next(x,None)
      print line

这是新的结果:

 mimi username
 passmimi real name
 mimi johnson username
 somejob real name
 john username
 passjohn real name
 jonathan username
 somejob real name(***im assuming this one is from john's job)

:/它没有做应该做的事

我建议使用正则表达式来解析此文件:

import re

# regex expression to parse the file as you provided it
# you could access the parseddata as a dict using the 
# keys "username", "password", "real_name" and "job"
ex = "\n*(?P<username>.+)\n(?P<password>.+)\n(?P<real_name>.+)\n(?P<job>.+)[\n\$]"

with open("usernames.txt", 'r') as users:
    matches = re.finditer(ex, users.read())
    for match in matches:
        user = match.groupdict()  # user is a dict

        # print username and real name
        print(user['username'], "username", user['real_name'], "real name")

编辑 :我认为这里实际上不需要正则表达式,因为此文件的格式非常简单。 所以这是不使用正则表达式的事情。

def parse(usersfile):
    # strip line break characters
    lines = (line.rstrip('\n') for line in usersfile)

    # keys to be used in the dictionnary
    keys = ('username', 'password', 'real_name', 'job')

    while True:
        # build the user dictionnary with the keys above
        user = {key: line for key, line in zip(keys, lines)}

        # yield user if all the keys are in the dict
        if len(user) == len(keys):
            yield user
        else:  # stop the loop
            break

with open("usernames.txt", 'r') as usersfile:
    for user in parse(usersfile):
        # print username and real name
        print(user['username'], "username", user['real_name'], "real name")

暂无
暂无

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

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