简体   繁体   English

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

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

I'm trying to write a code that iterates through a txt file and only gets the lines I want to print them out. 我正在尝试编写一个遍历txt文件的代码,只获取我要打印出来的行。

the text file should look like so: 文本文件应如下所示:

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

and so on. 等等。 this text file contains basically a user information (for a log in). 该文本文件基本上包含用户信息(用于登录)。 I need to make everyone's username print out and their real name (ex: mimi and mimi johnson.) and only those. 我需要打印出每个人的用户名和真实姓名(例如:mimi和mimi johnson)。 I don't want the current user's info to print out (in this ex: joji) 我不想打印当前用户的信息(在此示例中:joji)

here is my code: 这是我的代码:

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

for whatever reason when I run this program and i print out the second **** i put, it prints out the username's twice. 不管出于什么原因,当我运行该程序并打印出第二个****时,它都会打印出两次用户名。 (so ex: (因此:

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

why is that? 这是为什么? it should print out 它应该打印出来

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

if someone could help me out i'd be really grateful i dont get python. 如果有人可以帮助我,我将非常感激我没有python。 Im also open to any other suggestions to do this. 我也愿意接受任何其他建议来做到这一点。

EDIT::: i tried making a change with a suggestion this is the outcome: 编辑:::我试图进行更改,建议是这样:

new block of code: 新的代码块:

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

this is the new outcome: 这是新的结果:

 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)

:/ its not doing what its supposed to :/它没有做应该做的事

I would recommend using regex to parse this file: 我建议使用正则表达式来解析此文件:

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")

Edit : I figured that regex was not really needed here as the format of this file is quite simple. 编辑 :我认为这里实际上不需要正则表达式,因为此文件的格式非常简单。 So here is the same thing without using regex. 所以这是不使用正则表达式的事情。

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