【问题标题】:Using python to find specific pattern contained in a paragraph使用python查找段落中包含的特定模式
【发布时间】:2015-08-26 19:12:46
【问题描述】:

我正在尝试使用 python 浏览文件,找到特定的信息,然后将其打印到终端。我正在寻找的信息包含在一个看起来像这样的块中:

\\Version=EM64L-G09RevD.01\State=1-A1\HF=-1159.6991675\RMSD=4.915e-11\RMSF=1.175e-07\ZeroPoint=0.0353317\

我希望能够获得HF=-1159.6991675 的信息。更一般地说,我希望脚本复制和打印\HF=WhateverTheNumberIs\

我设法制作了能够复制整行并将其打印到终端的脚本,但我不确定如何完成这项特定任务。

【问题讨论】:

    标签: python data-processing


    【解决方案1】:

    我的建议是使用正则表达式 (regex) 来捕捉所需的模式:

    import re #for using regular expressions
    s = open(<filename here>).read() #read the content of the file and hold it as a string to be scanned
    p = re.compile("\HF=[^\]+", re.flags)  #p would be the pattern as you described, starting with \HF= till the next \)
    print p.findall(s) #finds all occurrences and prints them 
    

    【讨论】:

      【解决方案2】:

      正则表达式就是答案,例如 r'/HF.*/'。

      教程:- regex tutorial

      一旦你学会了正则表达式,它就是不可或缺的资源。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-02
        • 1970-01-01
        • 2018-05-04
        • 1970-01-01
        • 2017-03-05
        相关资源
        最近更新 更多