Python 文本格式处理问题

文本如下

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

Python 文本格式处理问题

12 回复

我的处理比较繁琐,坐等楼下大佬回答。


我无法理解你的问题

笨方法:根据换行 split 后。遍历。再根据特定的条件,去拼接。。、

第一反应是正则 不知道楼下大佬有没有简单方法

cinfigparser 模块吧 这个明显符合 windows 配资文件的格式 然后直接解析成字典

如果 Storage total storage 这些都是固定的话,用正则可以这么写:
Storage (\d+):\ntotal storage = (.+)\nfree storage = (.+)

如果不固定的话还是别用正则了,逐行遍历可能没那么麻烦。

for line in file:
if line[-1:] == ‘:’:
prefix = line[:-1].replace(’ ‘, ‘’)
else:
print (prefix+’
’+line.replace(’ ', ‘_’, 1))

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)
差不多就这样

sad,空格被吃掉了

configparser +1

python3<br>for line in open("new.txt", "r"):<br> line = line.rstrip()<br> if line.startswith("Storage "):<br> storage = line.rstrip(':')<br> else:<br> key, val = map(lambda x:x.strip(), line.split('='))<br> new_key = f"{storage}_{key}".replace(' ', '_')<br> print(f"{new_key} = {val}")<br>

6 楼的思路不错啊。学到了。replace 竟然有第三个参数。以前一直不知道

回到顶部