使用循环时如何在python3词典中使用制表 [英] How to use tabulate in python3 dictionary while using loops

查看:71
本文介绍了使用循环时如何在python3词典中使用制表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字典数据打印成表格形式,现在我认为tabulate模块是一种简单的测试方法,但是以某种方式获得的数据是很好的方法,但是header信息在每次运行中都重复输入用户ID,请提供指导或建议操作方法.....

I'm trying to print the dictionary data into a tabular form , for now i see tabulate module as a easy way to test but somehow the data i'm getting thats coming the good way but the header informaion is repeating on each run for the user ID, please guide or suggest how to do that.....

$ cat checktable.py
#!/usr/bin/python3
import subprocess
import pandas as pd
from tabulate import tabulate

def CheckUid(user):
    proc = subprocess.Popen("ldapsearch -h ldapserver  -D 'cn=directory manager' -w pass123 -LLLb 'ou=people,o=rraka.com'  'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    split_str = info_str.split()
    if len(split_str) > 1:
      raw_data = {'UserID': [split_str[1].split(',')[0].split('=')[1]], 'MangerID': [split_str[-1]]}
      headers = ["UserID", "MangerID"]
      return tabulate(raw_data, headers, tablefmt="simple")
    else:
      split_str = 'null'

def CallUid():
      with open('hh', mode='rt', encoding='utf-8') as f:
        for line in f.readlines():
         print(CheckUid(line))


if __name__ == '__main__':
    CallUid()

这将返回以下数据:

This returns the below data:

$ ./checktable.py
UserID    MangerID
--------  ----------
aashishp  rpudota
UserID    MangerID
--------  ----------
abaillie  davem
UserID    MangerID
--------  ----------
abishek   kalyang
UserID    MangerID

预期输出:

Expected output:

$ ./checktable.py
UserID    MangerID
--------  ----------
aashishp  rpudota
abaillie  davem
abishek   kalyang

另一个替代代码:

Another alternative code:

#!/usr/bin/python3
import sys
import subprocess
from tabulate import tabulate

def CheckUid(user):
    proc = subprocess.Popen("ldapsearch -h its3  -D 'cn=directory manager' -w JatetRE3 -LLLb 'ou=people,o=cadence.com'  'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    split_str = info_str.split()
    if len(split_str) > 1:
      raw_data = {'UserID': split_str[1].split(',')[0].split('=')[1], 'Manger': split_str[-1]}
      for key, value in raw_data.items():
        print(key, ":", value)
    else:
      split_str = 'null'

def CallUid():
  with open('hh', mode='rt', encoding='utf-8') as f:
    for line in f.readlines():
      CheckUid(line)

if __name__ == '__main__':
  CallUid()

如下所示,我需要每两行将两行合为一体..

It comes as below, where i need every two line two be into one..

$ ./checktable2.py
UserID : aashishp
Manger : rpudota
UserID : abaillie
Manger : davem

希望的是:

While desired would be:

$ ./checktable2.py
UserID : aashishp Manger : rpudota
UserID : abaillie Manger : davem

推荐答案

在努力学习之后,我想到了以下代码变体来解决自己的问题:

After Struggling as a learner, I came around with the below variant of codes as a solution to my own questions:

1)第一个代码正在使用pandas模块:

1) The First code is using the pandas module:

$ cat check_ldapUserdata.py
#!/usr/bin/python3
import pandas as pd
import subprocess

user_list = []
mngr_list = []

def CheckUid(user):
    proc = subprocess.Popen("ldapsearch -h ldapserver -D 'cn=directory manager' -w JatetRE3 -LLLb 'ou=people,o=rraka.com' 'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    split_str = info_str.split()
    if len(split_str) > 1:
      user = split_str[1].split(',')[0].split('=')[1]
      manager = split_str[-1]
      user_list.append(user)
      mngr_list.append(manager)
    else:
      split_str = 'null'

def DataList():
      df = pd.DataFrame({'User':user_list, 'Manager':mngr_list})
      df = df[['User', 'Manager']]  # To keep the order of columns
      #return df
      print(df)

def CallUid():
  with open('testu', mode='rt', encoding='utf-8') as f:
    for line in f.readlines():
      CheckUid(line)

if __name__ == '__main__':
  CallUid()
  DataList()

结果输出如下...

$ ./check_ldapUserdata.py
       User   Manager
0      karn  benjamin
1     niraj   vikashg
2  vaithees  benjamin
3      mauj  benjamin

2)我使用正则表达式& BeautifulTable模块获取表格式.

2) The another way I achived it with using Regular Expression & BeautifulTable module to get the table Format..

$ cat check_ldapUserdata2.py
#!/usr/bin/python3
import re
import subprocess
from beautifultable import BeautifulTable
table = BeautifulTable()
table.column_headers = ["User", "Manager"]

def CheckUid(user):
    proc = subprocess.Popen("ldapsearch -h ldapserver  -D 'cn=directory manager' -w pass123 -LLLb 'ou=people,o=rraka.com' 'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    pat_match = re.match(".*uid=(.*?)\,.*\nmanagerlogin:\s+(.*)",info_str)
    if pat_match:
        table.append_row([pat_match.group(1), pat_match.group(2)])

def CallUid():
  input_file=input("Please enter the file name : ")
  with open(input_file, mode='rt', encoding='utf-8') as f:
    for line in f.readlines():
      CheckUid(line)
  print(table)

if __name__ == '__main__':
  CallUid()

结果输出如下....

$ ./check_ldapUserdata2.py
Please enter the file name : testu
+----------+----------+
|   User   | Manager  |
+----------+----------+
|   karn   | benjamin |
+----------+----------+
|  niraj   | vikashg  |
+----------+----------+
| vaithees | benjamin |
+----------+----------+
|   mauj   | benjamin |
+----------+----------+

3)另一个简单的非表格形式,但是可以正常工作..

3) Another Simple non tabular Form but working ..

$ cat check_table_working1.py
#!/usr/bin/python3
import subprocess

def CheckUid(user):
    proc = subprocess.Popen("ldapsearch -h ldapserver -D 'cn=directory manager' -w pass123 -LLLb 'ou=people,o=rraka.com' 'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    split_str = info_str.split()
    if len(split_str) > 1:
      raw_data = {split_str[1].split(',')[0].split('=')[1] :  split_str[-1]}
      #raw_data = {'UserID': split_str[1].split(',')[0].split('=')[1], 'Manger': split_str[-1]}
      for key, value in raw_data.items():
        #print(key, ":", value)
        print('{} : {}'.format(key, value))
    else:
      split_str = 'null'

def CallUid():
  with open('hh', mode='rt', encoding='utf-8') as f:
    for line in f.readlines():
      CheckUid(line)

if __name__ == '__main__':
  CallUid()

以上结果输出如下...

Result output of the above is as below...

$ ./check_table_working1.py
aashishp : rpudota
abaillie : davem
abishek : kalyang
adik : venky
adithya : jagi

这篇关于使用循环时如何在python3词典中使用制表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆