2019-03-26 日常小程序

两个小程序都是读写文件:

一个是txt(open() write())
另一个是excel(dataframe.to_excel/itertuples/(×iterrows),getattr())
1、txt程序:
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 21 16:40:14 2019

@author: HOU Jinxiu
"""
import numpy as np
import copy
def read(path):
    with open(path,'r') as f:
        file = f.readlines()
    return file

def write(path,w_str):
    wopen=open(path,'w')
    for i in w_str:
        wopen.write(i)


def main():
    #读取swi文件获取带有调速器参数的发电机名称
    #输入swi文件路径
    #输出 -- 发电机名称 -- /EXC: --/PSS: --/GOV
    dir_swi = r'C:\Users\HOU\Desktop\待办\待消缺\03.21华东调速器参数映射\华东孤网BPA\BPA10018838.swi'
    name = []
    with open(dir_swi,'r') as f:
        swi = f.readlines()
    swi_select = []
    for line in swi:
        if line.startswith('..') and 'GOV' in line:
                swi_select.append(line.replace('套用',' ').split(' '))
                name.append(line.replace('套用',' ').split(' ')[1])                      
    print('有\033[1;31;43m %d \033[0m台发电机有调速器'%len(swi_select))

    #检查是否在潮流中该节点是否存在,若注释,则打开该节点。  
    #检查目标文件中是否包含相应发电机
    #这两个机器需要手动匹配:浙新城Y1、浙新城Y2
    dir_Target_S5 = r'C:\Users\HOU\Desktop\待办\待消缺\03.21华东调速器参数映射\19年上半年发布\ST.S5'
    with open(dir_Target_S5,'r') as f1:
        lines = f1.readlines()
        include = []
        for line in lines:
            for name_i in name:
                if name_i in line:
                    include.append(name_i)
                else:
                    pass       
    exclusive = list(set(name).difference(set(include)))
    print('BPA发电机名称和PSASP名称不一致的发电机台数有\033[1;31;43m %d \033[0m台\n名称不一致的发电机是:\033[0;31m%s\033[0m'%(len(exclusive),str(exclusive)))

    #从生产的工程中提取相应发电机的调速器参数组号和行号 
    #输入 S5文件地址和 L1文件地址
    #输出 --名称--类型---行号--
    dir_S5 = r'C:\Users\HOU\Desktop\待办\待消缺\03.21华东调速器参数映射\hdts01\Temp\BPA10018838.S5'
    dir_L1 = r'C:\Users\HOU\Desktop\待办\待消缺\03.21华东调速器参数映射\hdts01\Temp\BPA10018838.L1'
    with open(dir_S5,encoding = 'utf-8',errors = 'ignore') as f:
        temps5 = f.readlines()      
    s5 = [] 
    for line in temps5:       
        s5.append(line.replace(' ','').split(','))
    with open(dir_L1,'r') as f:
        templ1 = f.readlines()      
    L1 = [] 
    for line in templ1:       
        L1.append(line.replace(' ','').split(',')) 
        
    #调速器参数 名称和数量校验
    #new_s5是从BPA S5提取的全部数据。list保存,且名称名称已改成L1中的名称
    new_s5 = []
    for s in s5:
        if int(s[6])!= 0:
            s[1] = L1[int(s[1])-1][0].replace('\'','')
            new_s5.append(s)
    #name_s5 L1中的名称的前五位            
    name_s5 = []
    for s_name in new_s5:
        name_s5.append(s_name[1][:5])  #s_name[1][:5]前五位的话都可以有调速器模型了
    
    s5_exclusive = list(set(name_s5).difference(set(name)))
    print("BPA转成PSASP文件中有调速器模型的发电机个数是\033[1;31;43m %d台:\033[0m"%len(name_s5))
    print('不能匹配的发电机台数有\033[0;31m%d\033[0m台\n不能匹配的发电机是:%s'%(len(s5_exclusive),str(s5_exclusive))) 
#    cha = list(set(name).difference(set(name_s5)))
    #name1是去除['浙新城Y1', '浙新城Y2']后的发电机名称表
    name1 = set(include).difference(set(exclusive))
    print(len(name1))
    #--名称--类型---行号-
    origin = []
    count0 = 0
    for na in new_s5:
        if na[1][:5] in name1:
            Name = new_s5[count0][1]
            Tgo  = new_s5[count0][6]
            Lgo  = new_s5[count0][7]
            origin.append([[Name],[Tgo],[Lgo]])
        else:
            print(na[1])
        count0 += 1
    origin = np.array(origin).reshape(-1,3)
    #DATALIB.DAT手动修改 #,GOV3 1→23  #,GOV4 1→410  #,GOV7 1→81  #,GOV3 1→178\  
    change = copy.deepcopy(origin) 
    for index,element in enumerate(change[:,1]):
        if  element == '3':
            change[index,2] = int(change[index,2])+ 22
        elif  element== '4':
            change[index,2] = int(change[index,2]) + 409            
        elif  element== '7':
            change[index,2] = int(change[index,2]) + 80            
        elif  element== '8':
            change[index,2] = int(change[index,2]) + 177        
    change=np.c_[change,np.zeros(len(change))]
    #修改离线库的S5文件
    target_s5 = r'C:\Users\HOU\Desktop\待办\待消缺\03.21华东调速器参数映射\19wutiao\ST.S5'
    t_s5 = read(target_s5)
    num = 0  
    S5 = r'C:\Users\HOU\Desktop\待办\待消缺\03.21华东调速器参数映射\ST.S5'
    wopen=open(S5,'w')
    for line in t_s5:
        for index,element in enumerate(change[:,0]):
            if element[0:5] in line:
                change[index,3] = float(change[index,3])+1
                if float(change[index,3]) >1:
                    print(change[index,0])
                else:
                    sub = '%3s,%4s'%(change[index,1],change[index,2])
                    line =  line[:29]+sub+line[37:]
                    num +=1
        wopen.write(line)
    wopen.close()
    print('文件已保存')        
    print('已替换%d行'%num)
#    t_data =read(target_datalib)
#    d_data = read(dir_datalib)
   return t_s5,change
 

if __name__ == '__main__':
    A,B = main()

excel提取数据:
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 21:13:21 2019

@author: HOU
"""

import os
import pandas as pd
import time
os.chdir(r'C:\Users\HOU\Desktop')
#xlutils:修改excel
wb_rz2 = pd.read_excel('2rz.xlsx',header = None)
wb_rz3 = pd.read_excel('3rz.xlsx',header = None)
#rz2_ok =[]
#start_1 =time.time()
#for index, row in wb_rz2.iterrows():
#    A = str(row[1])
#    B = str(row[2])
#    count = 0
#    for index, row1 in wb_rz2.iterrows():
#        if A == str(row1[1]) and  B==str(row1[2]):
#            count += 1
#    if count>=2:
#        rz2_ok.append(list(row))
#time_1 = time.time()- start_1
rz2_ok =[]
start_1 =time.time()
for row in wb_rz2.itertuples(index=False):
    A = getattr(row,'_1')
    B = getattr(row,'_2')
    count = 0
    for row1 in wb_rz2.itertuples(index=False):
        if A == getattr(row1,'_1') and B==getattr(row1,'_2') :
            count += 1
    if count>=2:
        rz2_ok.append(list(row))
time_1 = time.time()- start_1
print('time A2:%s'%time_1)

start_2 =time.time()
rz3_ok =[]
for row in wb_rz3.itertuples(index=False):
    A = getattr(row,'_1')
    B = getattr(row,'_2')
    C = getattr(row,'_3')
    count = 0
    for row1 in wb_rz3.itertuples(index=False):
        if A == getattr(row1,'_1') and B==getattr(row1,'_2') and C==getattr(row1,'_3'):
            count += 1
    if count>=2:
        rz3_ok.append(list(row))
time_2 = time.time()- start_2
print('time A3:%s'%time_2)

    
rz2 =pd.DataFrame(rz2_ok)    
rz3 =pd.DataFrame(rz3_ok)    
rz2.to_excel('A2.xlsx',header = False)
rz3.to_excel('A3.xlsx',header = False)    

你可能感兴趣的:(2019-03-26 日常小程序)