Skip to main content
 首页 » 编程设计

python从文本文件中提取数字并将它们存储在列表列表中

2025年02月15日12cloudgamer

我有一个文本文件。我只想存储文本中的数字。例如:这是文件中的文本

ihlisdf 0.11 husj 0.2 khlkhhb,mbx blabla 2.2 fjd 3.3 0.5 jdkjkd 4.4

我需要脚本来只保存像这样的列表列表中的数字

[[0.11,0.2,2.2],[3.3,0.5,4.4]]

我尝试了以下方法

postemp=open('positionfile.txt','r') 
 
str=postemp.read() 
postemp.close() 
c=re.findall('\d+.\d+', str) 
 
i=0 
new_list=[] 
while i<len(c): 
  new_list.append(c[i:i+3]) 
  i+=3 

但它将数字存储为字符串。我需要像 float 这样的数字,因为我必须用它们做一些微积分

请您参考如下方法:

我就是这样做的。

如果你想让我解释什么,请告诉我

import numpy as np 
import re 
with open('positionfile.txt') as  f: 
    str = f.read() 
    s = re.findall('\d+\.?\d+?', str) 
    # the below converts the 1 dimensional vexotr into a 2 dimensional matrix with width 3 
    list = np.array(s).reshape(len(s)/3, 3).astype(float) 
 
 
print list 

输出:

[[ 0.1  0.2  2.2] 
 [ 3.3  0.5  4.4]]