2015-01-30 5 views
0

안녕하세요, 저는 python을 처음 접했을 때 다음 기준에 따라 PYTHON 3.4를 사용하여/etc/passwd 파일을 정렬하려고합니다 : 입력 (일반/etc/passwd 파일의 linux 시스템 : 나는 파일 중 하나를 찾고 또는 화면으로 돌아하고파이썬에서 파일의 내용 정렬

raj:x:501:512::/home/raj:/bin/ksh 
ash:x:502:502::/home/ash:/bin/zsh 
jadmin:x:503:503::/home/jadmin:/bin/sh 
jwww:x:504:504::/htdocs/html:/sbin/nologin 
wwwcorp:x:505:511::/htdocs/corp:/sbin/nologin 
wwwint:x:506:507::/htdocs/intranet:/bin/bash 
scpftp:x:507:507::/htdocs/ftpjail:/bin/bash 
rsynftp:x:508:512::/htdocs/projets:/bin/bash 
mirror:x:509:512::/htdocs:/bin/bash 
jony:x:510:511::/home/jony:/bin/ksh 
amyk:x:511:511::/home/amyk:/bin/ksh 

출력 :

1) Open and read the whole file or do it line by line 
2) Loop through the file using python regex 
3) Write it into temp file or create a dictionary 
4) Print the dictionary keys and values 
: 여기

Group 511 : jony, amyk, wwwcorp 
Group 512 : mirror, rsynftp, raj 
Group 507 : wwwint, scpftp 
and so on 

내 계획입니다

이 예제를 어떻게 효율적으로 수행 할 수 있는지 또는 모든 정렬 알고리즘을 적용 해 주시면 정말 감사하겠습니다. 감사합니다.

+1

에 모든 사용자를 던질 수 있습니다. 그냥 ":"로 분리하고 이름 (0 번째 요소)과 gid (3 번째 요소)를 가져옵니다. –

답변

3

당신은 파일을 열 목록에 던져 다음 몇 가지 좀 해시 테이블 당신은 이것에 대한 정규식이 필요하지 않습니다

with open("/etc/passwd") as f: 
    lines = f.readlines() 

group_dict = {} 
for line in lines: 
    split_line = line.split(":") 
    user = split_line[0] 
    gid = split_line[3] 
    # If the group id is not in the dict then put it in there with a list of users 
    # that are under that group 
    if gid not in group_dict: 
     group_dict[gid] = [user] 
    # If the group id does exist then add the new user to the list of users in 
    # the group 
    else: 
     group_dict[gid].append(user) 

# Iterate over the groups and users we found. Keys (group) will be the first item in the tuple, 
# and the list of users will be the second item. Print out the group and users as we go 
for group, users in group_dict.iteritems(): 
    print("Group {}, users: {}".format(group, ",".join(users))) 
+0

Greg에게 감사의 말을 전합니다. 제 2 부분에 대한 코멘트를 달아서 흐름을 더 잘 이해할 수 있습니다. – Zerg12

+0

코드에 몇 가지 설명을 추가했습니다. 파이썬 문서는 또한 문법의 일부를 이해하는 데 어려움이있는 경우에도 매우 유용합니다. – Greg

+0

고맙습니다. 이제는 수정되었습니다! – Zerg12

1

/etc/passwd을 반복하고 그룹별로 사용자를 정렬해야합니다. 이 문제를 해결하기 위해 아무 것도 할 필요가 없습니다.

with open('/etc/passwd', 'r') as f: 
    res = {} 

    for line in f: 
     parts = line.split(':') 

     try: 
      name, gid = parts[0], int(parts[3]) 
     except IndexError: 
      print("Invalid line.") 
      continue 

     try: 
      res[gid].append(name) 
     except KeyError: 
      res[gid] = [name] 

for key, value in res.items(): 
    print(str(key) + ': ' + ', '.join(value)) 
+0

나쁘지 않아, Andreas. FWIW, 우리는 (주로) 4 칸 정도의 들여 쓰기를 선호합니다. 'res = {}'다음에 불필요한';'을 사용하고,'res'보다 약간 의미있는 이름을 사용할 수있는 좋은 습관을 Python 초보자에게 가르쳐야합니다. 'IndexError'를 테스트하려고한다면 아마도 자동으로 계속하기보다는 오류 메시지를 출력해야합니다. 또한, 왜 그냥'IndexError'를 테스트하고 ValueError : int()는 유효하지 않은 리터럴을 테스트할까요? 그러나 'dict'삽입에 [EAFP] (https://docs.python.org/3/glossary.html#term-eafp)를 사용하는 것에 대한 명성. –

+0

감사합니다. Andreas, 코드를 더 잘 이해할 수 있도록 덧글을 달 수있는 기회가 있습니까? – Zerg12

+0

@ Zerg12 : 공식 파이썬 튜토리얼의'try : ... except'에있는 섹션을 읽어야합니다 : [오류 및 예외] (https://docs.python.org/3/tutorial/errors.html). Andreas 코드의 대부분을 이해하는 데 도움이됩니다. –