推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
awker
V2EX  ›  Python

Python 文本格式处理问题

  •  
  •   awker · May 24, 2019 · 3795 views
    This topic created in 2720 days ago, the information mentioned may be changed or developed.

    文本如下

    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
    
    11 replies  •  2019-05-24 22:14:14 +08:00
    zhila
    zhila
    May 24, 2019
    1
    我的处理比较繁琐,坐等楼下大佬回答。
    csdreamdong
    csdreamdong
    May 24, 2019
    2
    笨方法:根据换行 split 后。遍历。再根据特定的条件,去拼接。。、
    V2tizen
    V2tizen
    May 24, 2019
    3
    第一反应是正则 不知道楼下大佬有没有简单方法
    fisher335
    fisher335
    May 24, 2019 via Android
    4
    cinfigparser 模块吧 这个明显符合 windows 配资文件的格式 然后直接解析成字典
    ysc3839
    ysc3839
    May 24, 2019
    5
    如果 Storage total storage 这些都是固定的话,用正则可以这么写:
    `Storage (\d+):\ntotal storage = (.+)\nfree storage = (.+)`

    如果不固定的话还是别用正则了,逐行遍历可能没那么麻烦。
    dairoot
    dairoot
    May 24, 2019
    6
    for line in file:
    if line[-1:] == ':':
    prefix = line[:-1].replace(' ', '_')
    else:
    print (prefix+'_'+line.replace(' ', '_', 1))
    Cooky
    Cooky
    May 24, 2019 via Android❤️2
    7
    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
    Cooky
    May 24, 2019 via Android
    8
    @Cooky sad,空格被吃掉了
    zeraba
    zeraba
    May 24, 2019 via Android
    9
    configparser +1
    omph
    omph
    May 24, 2019❤️1
    10
    ```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
    jianghu52
    May 24, 2019
    11
    6 楼的思路不错啊。学到了。replace 竟然有第三个参数。以前一直不知道
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2624 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 15:04 · PVG 23:04 · LAX 07:04 · JFK 10:04
    ♥ Do have faith in what you're doing.