Skip to main content
 首页 » 编程设计

python之如何从文本文件中捕获未注释的代码行

2024年10月25日8lexus

我有一个这样的文本文件:

#<[_MOUNTING] Recessed 
#<[_FAMILY] RT8 
#<[_PRODUCTID] cecf8545-0ff3-4d4a-bafd-dbb156bab282 
#<[_BALLAST_TYPE] ELECTRONIC 
#<[_FIXTURE_TYPE] 2X4 Volumetric 
#<[_TERCAT] Recessed, Linear 
#<[_TER] 72 
# 54.8 watt luminaire, lamp*ballast factor = 1 
 
void brightdata 2RT8S_2_32_LP735_dist 
23 flatcorr C:/rm/ies/2RT8S_2_32_LP735.dat source.cal src_phi4 src_theta -i 1 -t 3.2 0.9 2.9 -i 0 -t 2.44 0.0 0.0 -i 0 -t -0.0 1.83 0.0 
0 
1            1.54935 
 
 
# c:\daysim\bin\xform -n a0.1 -t 3.2 0.9 2.9 -i 0 -t 2.44 0.0 0.0 -i 1 -t -0.0 1.83 0.0 
# c:\daysim\bin\ies2rad -dm -m 0.95 -t white -o C:/rm/ies/2RT8S_2_32_LP735 
# Dimensions in meters 
#<[_PRODUCTID] cecf8545-0ff3-4d4a-bafd-dbb156bab282 
#<[_BALLAST_TYPE] ELECTRONIC 
#<[_FIXTURE_TYPE] 2X4 Volumetric 
#<[_TERCAT] Recessed, Linear 
#<[_TER] 72 
# 54.8 watt luminaire, lamp*ballast factor = 1 
 
void brightdata 2RT8S_2_32_LP735_dist 
23 flatcorr C:/rm/ies/2RT8S_2_32_LP735.dat source.cal src_phi4 src_theta -i 1 -t 3.2 0.9 2.9 -i 0 -t 2.44 0.0 0.0 -i 1 -t -0.0 1.83 0.0 
0 
1            1.54935 
 
2RT8S_2_32_LP735_dist light 2RT8S_2_32_LP735_light 
0 
0 
3                  1                  1                  1 
 
# c:\daysim\bin\xform -n a0.2 -t 3.2 0.9 2.9 -i 0 -t 2.44 0.0 0.0 -i 2 -t -0.0 1.83 0.0 
# c:\daysim\bin\ies2rad -dm -m 0.95 -t white -o C:/rm/ies/2RT8S_2_32_LP735 
# Dimensions in meters 
#<IESNA:LM-63-2002 
#<[TEST] LTL18481 
#<[TESTDATE] 1/28/2010 

我想捕获未注释的代码行并将它们写入单独的文件中。如果找不到更好的词,最“pythonic”的方法是什么?我已经让它工作了,但是我认为我的方式不是很优雅。我的代码如下。

from __future__ import print_function 
lumdict={} 
counter = 1 
b =False 
 
with open(radFile) as rad: 
    a=[] #Create a temp list to capture noncommented data. 
    for lines in rad: 
 
        if not lines.startswith("#"): 
            a.append(lines) #Add non commented data to templist 
        else: 
            if len(a)>0:  
                lumdict[counter]=a #Capture non commented data into a dictionary. 
                b=a[:] #This is the list meant to be used for the last bit of non commented data. 
                a=[] 
                counter +=1 
    else: 
        lumdict[counter]=b 
 
 
for zones,radvalues in lumdict.items(): #Write the dictionary to individual files. 
    with open(r'd:\zones\{}.rad'.format(zones),'w') as zonefile: 
        for lines in radvalues: 
            print(lines,file=zonefile,end="") 

请您参考如下方法:

您可以在迭代时写入文件,而不是使用以下内容创建字典:

from __future__ import print_function 
 
with open(radFile) as rad: 
    counter = 0 
    zonefile = open(r'd:\zones\{}.rad'.format(counter),'w') 
    for line in rad: 
        if not line.startswith("#"): 
            if zonefile.closed: 
                counter += 1 
                zonefile = open(r'd:\zones\{}.rad'.format(counter),'w') 
            print(line, file=zonefile) 
        else: 
            zonefile.close() 
    zonefile.close()