Python将表数据解析为数组

2024-10-03 00:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文

首先我使用的是python2.7。你知道吗

我试图实现的是将activedirectory查找中的表数据分离为数组中的“Firstname Lastname”项,稍后我可以将这些项与另一个数组进行比较,并查看列表中哪些用户不匹配。你知道吗

我运行dsquery group domainroot -name groupname | dsget group -members | dsget user -fn -ln,输出如下列表:

  fn               ln               
  Peter            Brill            
  Cliff            Lach          
  Michael          Tsu               
  Ashraf           Shah             
  Greg             Coultas          
  Yi               Li               
  Brad             Black            
  Kevin            Schulte          
  Raymond          Masters (Admin)  
  James            Rapp            
  Allison          Wurst            
  Benjamin         Hammel            
  Edgar            Cuevas           
  Vlad             Dorovic (Admin)        
  Will             Wang                        
dsget succeeded

请注意,此列表在每个数据集之前和之后都有空格。你知道吗

我当前使用的代码:

userarray = []
p = Popen(["cmd.exe"], stdin=PIPE, stdout=PIPE)
p.stdin.write("dsquery group domainroot -name groupname | dsget group -members | dsget user -fn -ln\n")
p.stdin.write("exit\n")
processStdout = p.stdout.read().replace("\r\n", "").strip("")[266:]
cutWhitespace = ' '.join(processStdout.split()).split("dsget")[0]
processSplit = re.findall('[A-Z][^A-Z]*', cutWhitespace)
userarray.append(processSplit)
print userarray
我的问题是,当我在空白空间上分割并尝试将它们重新分组为“FieldNestLtNeNT”时,它命中列表中的行(admin),因为有第三个字段,所以分组被抛出。以下是我的意思示例:

['Brad ', 'Black ', 'Kevin ', 'Schulte ', 'Raymond ', 'Masters (', 'Admin) ', 'James ', 'Rapp ', 'Allison ', 'Wurst ',

我将感谢任何关于如何更好地或正确地分组的建议。谢谢!你知道吗


Tags: 数据name列表adminstdingroup数组fn
2条回答
# the whole file.
content = p.stdout.read()
# each line as a single string
lines = content.split()
# lets drop the header and the last line
lines = lines[1:-1]
# Notice how the last name starts at col 19
names = [(line[:19].strip(), line[19:].strip()) for line in lines]
print(names)
=> [('Peter', 'Brill'), ('Cliff', 'Lach'), ('Michael', 'Tsu'), ('Ashraf', 'Shah'), ('Greg', 'Coultas'), ('Yi', 'Li'), ('Brad', 'Black'), ('Kevin', 'Schulte'), ('Raymond', 'Masters (Admin)'), ('James', 'Rapp'), ('Allison', 'Wurst'), ('Benjamin', 'Hammel'), ('Edgar', 'Cuevas'), ('Vlad', 'Dorovic (Admin)'), ('Will', 'Wang')]

现在,如果列大小发生了变化,只需在删除头之前执行index = lines[0].indexof('ln'),并使用它而不是19

split有一个maxsplit参数,您可以告诉它只拆分第一个分隔符,这样您就可以说:

cutWhitespace = ' '.join(processStdout.split(None,1)).split("dsget")[0]

在你的第六行告诉它不要再分裂一次。你知道吗

相关问题 更多 >