如何为一个表达式编写正则表达式?

时间:2019-10-08 10:27:37

标签: python

我想从一个文件中提取所有以chdir('../'); echo getcwd(); 开头的句子 我只想显示这些句子中的所有值:

info clockdritf [syncCLK_predict]: predict_part_corr

这是我的职能,但我没有给我任何结果:

info clockdritf [syncCLK_predict]: predict_part_corr -1
info clockdritf [syncCLK_predict]: predict_part_corr  5
info clockdritf [syncCLK_predict]: predict_part_corr  8
info clockdritf [syncCLK_predict]: predict_part_corr -7
info clockdritf [syncCLK_predict]: predict_part_corr 15

获得的结果:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')
from collections import OrderedDict
from pylab import *
import csv
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import seaborn as sns
sns.set_style('whitegrid')

#info clockdritf [syncCLK_predict]: predict_part_correction -1

try:
    import uncertainties.unumpy as unp
    import uncertainties as unc
except:
    import pip

    pip.main(['install', 'uncertainties'])
    import uncertainties.unumpy as unp
    import uncertainties as unc

Synchronization_Signals_Counter= OrderedDict ({
    'clkpredict':r'info\sclockdritf\s[syncCLK_predict]:\spredict_part_corr\s+([0-9]+)'
})

def Extract_List_Data_Info_Based_On_Regular_Expression(Log_File, re_key):
    # print(re_key)
    re_value = Synchronization_Signals_Counter[re_key]
    fsrc = open(Log_File, 'r')
    buff = fsrc.read()
    list_info = re.findall(re_value, buff)
    print(list_info)
    list_info[0]= ('clkpredict')
    return(list_info)

if __name__ == '__main__':
    Log_File='/home/ptl/Simulations/Results.log'

    for re_key in Synchronization_Signals_Counter.keys():
        print(re_key)
        list_info=Extract_List_Data_Info_Based_On_Regular_Expression(Log_File, re_key)
        print(list_info)

2 个答案:

答案 0 :(得分:0)

代替使用正则表达式,您可以使用rsplit()方法将字符串从右开始拆分为列表:

values = []
with open("log.txt") as f:
    for line in f.readlines():
        values.append(int(line.rstrip().rsplit(" ", 1)[1]))

答案 1 :(得分:0)

[int(line.split("info clockdritf [syncCLK_predict]: predict_part_corr")[-1]) for line in open("_your_file_path_here_", 'r').readlines()]