如何分隔和显示字符串值,后跟分配给变量的整数值?

时间:2017-01-31 17:23:57

标签: python csv

Below is the screenshot of .csv file

我有一个.csv文件,它包含分配给其中不同变量的字符串和整数值,如上图所示:

使用以下代码,我可以检索如下:

import csv
import time
from datetime import datetime as dt

with open('test.csv') as infile:
    headers = next(csv.reader(infile))

with open('test.csv') as infile:
    for row in csv.DictReader(infile):
        try:
            line_protocol = ""
            row['Time:']=str(time.mktime(time.strptime(row['Time:'], '%d-%b-%Y %H:%M:%S:%f')))
            line_protocol =  "Power,"+(','.join(["%s = %s" %(header, row[header]) for header in headers if header != 'Time:']))+"\t\t "+row['Time:']
            for row in csv.DictReader(infile):
                new_item=[item for item in line_protocol if not item.isdigit()]
                print (new_item)
                print("\n\n",line_protocol)
        except ValueError:
            pass

上述代码的输出:

Power,Bat1-Vol = 37.4377,Bus1V-BeforeEMR = 37.5398,Bus1-V-AfterEMR = 37.5398,SA1-Cur = -0.0416,Bat1-Cur-Low-M = -0.8011,Bat1-Cur-Low-R = -0.8051,Dom-Reg-1-OVP = NotActed,Bat1-Cur-High-R = 0,Bus1-Load-Cur = 0.7595,Bus-Config = Isolate        1473230069.0
['P', 'o', 'w', 'e', 'r', ',', 'B', 'a', 't', '-', 'V', 'o', 'l', ' ', '=', ' ', '.', ',', 'B', 'u', 's', 'V', '-', 'B', 'e', 'f', 'o', 'r', 'e', 'E', 'M', 'R', ' ', '=', ' ', '.', ',', 'B', 'u', 's', '-', 'V', '-', 'A', 'f', 't', 'e', 'r', 'E', 'M', 'R', ' ', '=', ' ', '.', ',', 'S', 'A', '-', 'C', 'u', 'r', ' ', '=', ' ', '-', '.', ',', 'B', 'a', 't', '-', 'C', 'u', 'r', '-', 'L', 'o', 'w', '-', 'M', ' ', '=', ' ', '-', '.', ',', 'B', 'a', 't', '-', 'C', 'u', 'r', '-', 'L', 'o', 'w', '-', 'R', ' ', '=', ' ', '-', '.', ',', 'D', 'o', 'm', '-', 'R', 'e', 'g', '-', '-', 'O', 'V', 'P', ' ', '=', ' ', 'N', 'o', 't', 'A', 'c', 't', 'e', 'd', ',', 'B', 'a', 't', '-', 'C', 'u', 'r', '-', 'H', 'i', 'g', 'h', '-', 'R', ' ', '=', ' ', ',', 'B', 'u', 's', '-', 'L', 'o', 'a', 'd', '-', 'C', 'u', 'r', ' ', '=', ' ', '.', ',', 'B', 'u', 's', '-', 'C', 'o', 'n', 'f', 'i', 'g', ' ', '=', ' ', 'I', 's', 'o', 'l', 'a', 't', 'e', '\t', '\t', ' ', '.']

在目前的代码中,只提取了字符串值,但我希望输出为所有字符串值后跟整数值,即

Power,**Bus-Config = Isolate,Dom-Reg-1-OVP = NotActed**,Bat1-Vol = 37.4377,Bus1V-BeforeEMR = 37.5398,Bus1-V-AfterEMR = 37.5398,SA1-Cur = -0.0416,Bat1-Cur-Low-M = -0.8011,Bat1-Cur-Low-R = -0.8051,Bat1-Cur-High-R = 0,Bus1-Load-Cur = 0.7595        1473230069.0

我尝试过使用RE,如下所示..

        try:
            line_protocol = ""
            row['Time:']=str(time.mktime(time.strptime(row['Time:'], '%d-%b-%Y %H:%M:%S:%f')))
            line_protocol =  "Power,"+(','.join(["%s = %s" %(header, row[header]) for header in headers if header != 'Time:']))+"\t\t "+row['Time:']
            for row in csv.DictReader(infile):
                for s in row:
                    print (re.findall("[-+]?\d+[\.]?\d*[eE]?[-+]?\d*",s))
            print("\n\n",line_protocol)
        except ValueError:
            pass

0 个答案:

没有答案