Skip to main content
 首页 » 编程设计

python之使用正则表达式读取和处理文件

2025年05月04日26kerrycode

我有一个巨大的文件,它只是这些 block 的重复单元:

//WAYNE ROONEY (wr10) 
  90 [label="90"]; 
  90 -> 11 [weight=25]; 
  90 -> 21 [weight=23]; 
  90 -> 31 [weight=17]; 
  90 -> 41 [weight=12]; 
  90 -> 51 [weight=1]; 
  90 -> 62 [weight=50]; 
  90 -> 72 [weight=7]; 
  90 -> 82 [weight=27]; 
  90 -> 92 [weight=9]; 
  90 -> 102 [weight=43]; 

我需要转换成这样的格式

90 11 25 

即我只需要删除所有多余的东西,并保持数字原样不变即可。

我尝试使用正则表达式,这行代码:

for line in filein: 
    match = re.search('label=" "', line) 
    if match: 
        print (match.group()) 

但它只是打印文件中 'label' 的所有实例。如果我尝试搜索 'label=""',则没有输出。如果我能知道如何阅读标签,那么阅读重量将与它非常相似。

请您参考如下方法:

这个怎么样:

import re 
 
file = open("file","r")                        
 
for line in file:                                  
    if re.search('->',line): 
        print ' '.join(re.findall('[0-9]+',line)) 

输出:

90 11 25 
90 21 23 
90 31 17 
90 41 12 
90 51 1 
90 62 50 
90 72 7 
90 82 27 
90 92 9 
90 102 43 

只需重定向以保存输出:python test.py > newfile