2016-08-15 3 views
0

txt 파일을 반복하는 코드를 작성하려고하는데 출력 할 줄만 가져옵니다.루프 (파이썬)에서 next()를 사용하여 다음 줄을 가져올 수 없습니다.

텍스트 파일과 같이 보일 것입니다 : 등등

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 
... 

내가 파이썬을 얻을 해달라고 인쇄해야 어떤 다른 임을 열 수도 있습니다. 제안은이 작업을 수행하는

편집을 ::: 난이 결과 인 제안과 변경을 시도 :.

코드의

새로운 블록 :

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) 

:/그 일을하지 무엇을 그 가정

에 나는이 파일을 구문 분석하는 정규식을 사용하는 것이 좋습니다 것입니다
+4

'next()'를 호출해도'line'의 값은 변경되지 않습니다. –

+0

그렇지 않습니까? 그러면 가장 좋은 방법은 무엇이겠습니까 – harekuin

+2

이 경우에 'next'의 반환 값을 캡처해야한다고 생각합니다. 예 : 'line = next (x)' –

답변

1

:

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

이 목록의 항목 앞에 사용자 이름과 암호가 있다고 가정합니까? (텍스트 파일에서와 같이) – harekuin

+0

첫 번째 줄은 사용자 이름이고 두 번째 줄은 암호이고, 세 번째 줄은 실제 이름이고 네 번째 줄은 암호라고 가정합니다. 이것이 네가 의미하는 바라면 네. ;) – odrling

+0

나는 읽을 수 없다. 너무 많이 반복해서 모든 일을 반복하고이 코드에서 배울 수있게 해줘서 고맙습니다. – harekuin