文本如下
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
|      1zhila      2019-05-24 18:08:28 +08:00 我的处理比较繁琐,坐等楼下大佬回答。 | 
|      2csdreamdong      2019-05-24 18:11:06 +08:00 笨方法:根据换行 split 后。遍历。再根据特定的条件,去拼接。。、 | 
|      3V2tizen      2019-05-24 18:11:49 +08:00 第一反应是正则 不知道楼下大佬有没有简单方法 | 
|      4fisher335      2019-05-24 18:17:05 +08:00 via Android cinfigparser 模块吧  这个明显符合 windows 配资文件的格式  然后直接解析成字典 | 
|  |      5ysc3839      2019-05-24 18:26:39 +08:00 如果 Storage total storage 这些都是固定的话,用正则可以这么写: `Storage (\d+):\ntotal storage = (.+)\nfree storage = (.+)` 如果不固定的话还是别用正则了,逐行遍历可能没那么麻烦。 | 
|  |      6dairoot      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)) | 
|  |      7Cooky      2019-05-24 18:33:29 +08:00 via Android  2 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) 差不多就这样 | 
|      9zeraba      2019-05-24 18:37:16 +08:00 via Android configparser +1 | 
|  |      10omph      2019-05-24 18:55:38 +08:00  1 ```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}") ``` | 
|      11jianghu52      2019-05-24 22:14:14 +08:00 6 楼的思路不错啊。学到了。replace 竟然有第三个参数。以前一直不知道 |