Skip to main content
 首页 » 编程设计

python之从python中的文本文件中读取数字

2024年10月24日13lvdongjie

我正在尝试从如下所示的文本文件中读取一列数字:

一些文本和数字...,然后:

 q-pt=    1    0.000000  0.000000  0.000000      1.0000000000 
   1      -0.066408              0.0000000                       
   2      -0.053094              0.0000000                       
   3      -0.037643              0.0000000  
   ... 
   156    3107.735577            6.8945617 
...more text file 

我有兴趣阅读包含 -0.066408、-0.053094 等的第二列。
我尝试编写的代码在某种程度上没有在没有给出任何错误的情况下完成工作。我试过这个:

import re                                                                             
import sys                                                                            
from string import atof                                                               
from math import exp                                                                  
from numpy import *                                                                   
 
file1 = open('castepfreq.dat', 'w')                                                   
with open('xd_geo_Efield.phonon') as file:                                            
    File = file.readlines()                                                           
    p1 = re.compile("q-pt=    1    0.000000  0.000000  0.000000      1.0000000000")   
    for i in range(len(File)):                                                        
        m1 = p1.search(File[i])                                                       
          if  m1:                                                                        
            read = int(float(File[i+1][10:23]))       
            freq = (read)                                                             
    print >> file1, freq     
file1.close() 

如果有人能帮我解决这个问题,那就太好了。

请您参考如下方法:

您可以在空格处拆分,然后提取第二个元素:

with open('xd_geo_Efield.phonon') as f: 
    col = [line.split()[1] for line in f] 
    print(col) 

如果您的输入是:

q-pt=    1    0.000000  0.000000  0.000000      1.0000000000 
1      -0.066408              0.0000000 
2      -0.053094              0.0000000 
3      -0.037643              0.0000000 

输出将是:

[('1', '-0.066408', '-0.053094', '-0.037643')] 

或者使用 itertools 和转置:

from itertools import izip, islice, imap 
with open('xd_geo_Efield.phonon') as f: 
    col = islice(izip(*imap(str.split,f)), 1,2) 
    print(list(col)) 

如果要转换,将值转换为 float :

 [float(line.split()[1]) for line in f] 

此外,如果您想跳过 header 并忽略 1,请在使用其余代码之前对文件对象调用 next(f),即:

with open('xd_geo_Efield.phonon') as f: 
      next(f) 
      col = [float(line.split()[1]) for line in f] 
      print(list(col)) 

哪个会输出:

 [-0.066408, -0.053094, -0.037643] 

如果您有想要忽略的数据并且只从 q-pt=.. 行开始,您可以使用 itertools.dropwhile 忽略开头的行:

from itertools import dropwhile 
 
with open('xd_geo_Efield.phonon') as f: 
    col = [float(line.split()[1]) for line in dropwhile( 
           lambda x: not x.startswith("q-pt="), f)] 
    print(list(col)) 

如果你也想忽略那一行,你可以再次调用 next 但这次是在 dropwhile 对象上:

from itertools import dropwhile 
 
with open('xd_geo_Efield.phonon') as f: 
    dp = dropwhile(lambda x: not x.startswith("q-pt="), f) 
    next(dp) 
    col = [float(line.split()[1]) for line in dp] 
    print(list(col)) 

所以对于输入:

some 1 1 1 1 1 
meta 2 2 2 2 2 
data 3 3 3 3 3 
and 4 4 4 4 4 
numbers 5 5 5 5 5 
q-pt=    1    0.000000  0.000000  0.000000      1.0000000000 
1      -0.066408              0.0000000 
2      -0.053094              0.0000000 
3      -0.037643              0.0000000 
3      -0.037643              0.0000000 

输出将是:

[-0.066408, -0.053094, -0.037643, -0.037643] 

对于前导空格,lstrip 去掉:

from itertools import dropwhile, imap, takewhile 
 
with open('xd_geo_Efield.phonon') as f: 
    # for python3 just use map 
    dp = dropwhile(lambda x: not x.startswith("q-pt="), imap(str.lstrip,f)) 
    next(dp) 
    col = [float(line.split(None,2)[1]) for line in takewhile(lambda x: x.strip() != "", dp)] 
    print(list(col)) 

takewhile 将继续取行,直到我们到达文件末尾的第一个空行。