Python 文本格式处理问题

2019-05-24 18:01:54 +08:00
 awker

文本如下

Storage 1:
total storage = 204699 MB
free storage = 195091 MB
Storage 2:
total storage = 204699 MB
free storage = 200661 MB

如何实现最终结果为

Storage_1_total_storage = 204699 MB
Storage_1_free_storage = 195091 MB
Storage_2_total_storage = 204699 MB
Storage_2_free_storage = 200661 MB
2399 次点击
所在节点    Python
11 条回复
zhila
2019-05-24 18:08:28 +08:00
我的处理比较繁琐,坐等楼下大佬回答。
csdreamdong
2019-05-24 18:11:06 +08:00
笨方法:根据换行 split 后。遍历。再根据特定的条件,去拼接。。、
V2tizen
2019-05-24 18:11:49 +08:00
第一反应是正则 不知道楼下大佬有没有简单方法
fisher335
2019-05-24 18:17:05 +08:00
cinfigparser 模块吧 这个明显符合 windows 配资文件的格式 然后直接解析成字典
ysc3839
2019-05-24 18:26:39 +08:00
如果 Storage total storage 这些都是固定的话,用正则可以这么写:
`Storage (\d+):\ntotal storage = (.+)\nfree storage = (.+)`

如果不固定的话还是别用正则了,逐行遍历可能没那么麻烦。
dairoot
2019-05-24 18:33:19 +08:00
for line in file:
if line[-1:] == ':':
prefix = line[:-1].replace(' ', '_')
else:
print (prefix+'_'+line.replace(' ', '_', 1))
Cooky
2019-05-24 18:33:29 +08:00
for line in text :
if line.startswith('Storage') :
s = line.strip().replace( ' ', '_' )[:-1 ]
else :
k,v = line.split('=')
k = k.strip().replace( ' ', '_' )
line = '%s_%s = %s' % ( s, k, v )
out.write(line)
差不多就这样
Cooky
2019-05-24 18:33:58 +08:00
@Cooky sad,空格被吃掉了
zeraba
2019-05-24 18:37:16 +08:00
configparser +1
omph
2019-05-24 18:55:38 +08:00
```python3
for line in open("new.txt", "r"):
line = line.rstrip()
if line.startswith("Storage "):
storage = line.rstrip(':')
else:
key, val = map(lambda x:x.strip(), line.split('='))
new_key = f"{storage}_{key}".replace(' ', '_')
print(f"{new_key} = {val}")
```
jianghu52
2019-05-24 22:14:14 +08:00
6 楼的思路不错啊。学到了。replace 竟然有第三个参数。以前一直不知道

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/567385

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX