Python 2:处理字符串

时间:2018-02-02 08:12:08

标签: python python-2.7

我需要获取有关我机器磁盘的信息,并且我使用psutil来做到这一点。但结果并不那么友好。所以我决定处理它,但我的代码看起来很傻。

oldstr = str(psutil.disk_partitions())
oldstr = oldstr.replace("sdiskpart(", "")
oldstr = oldstr.replace(")", "")
oldstr = oldstr[1:-1]
oldstr = oldstr.split(",")

结果如下所示:

["device='C:\\\\'", " mountpoint='C:\\\\'", " fstype='NTFS'", " opts='rw", "fixed'", " device='D:\\\\'", " mountpoint='D:\\\\'", " fstype='NTFS'", " opts='rw", "fixed'"]

我期望的结果是这样的:

["C:\\", "C:\\", "NTFS", "rw, fixed", "D:\\", "D:\\", "NTFS", "rw, fixed"]

有没有人有更好的主意? 请与我分享您的想法。 非常感谢, 广

2 个答案:

答案 0 :(得分:0)

理想情况下,您不应该将结果从psutil.disk_partitions()转换为字符串然后解析它。相反,它返回的是sdiskpart()的对象,其成员为['device','mountpoint','fstype','opts']

这是一个天真的解决方案:

final_result = []
part_results = psutil.disk_partitions()
for disk in part_results:
    final_result.append(disk.device)
    final_result.append(disk.mountpoint)
    final_result.append(disk.fstype)
    final_result.append(disk.opts)

# Some of these results could be '' (Empty Strings)
# Strip them out as required.
print final_result

您现在拥有预期的结果

["C:\\", "C:\\", "NTFS", "rw, fixed", "D:\\", "D:\\", "NTFS", "rw, fixed"]

替代方法如下,返回OrderedDict

的列表
part_results = [part.__dict__ for part in psutil.disk_partitions()]

然后,您可以在键值对之间循环,并根据需要将它们附加到数组中。这是上面一行代码的示例输出。

[OrderedDict([('device', 'C:\\'), ('mountpoint', 'C:\\'), ('fstype', 'NTFS'), ('opts', 'rw,fixed')]),
OrderedDict([('device', 'D:\\'), ('mountpoint', 'D:\\'), ('fstype', 'NTFS'), ('opts', 'rw,fixed')])]

答案 1 :(得分:-2)

添加如何:

oldstr = [i.split('=') for i in oldstr]
oldstr = [x[1] if len(x) == 2 else x[0] for x in oldstr]

然后resut看起来像:

["'C:\\\\'", "'C:\\\\'", "'NTFS'", "'rw", "fixed'", "'D:\\\\'", 
"'D:\\\\'", "'NTFS'", "'rw", "fixed'"]