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

标签 python regex

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

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]]

关于python从文本文件中提取数字并将它们存储在列表列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41051297/

相关文章:

python - 从外部源更改 Django 的设置

python 将 beautifulsoup 输出转换为 dict/json

regex - 解析ansible中的字符串列表

正则表达式匹配行尾

python - 用计算值声明模块级常量的 pythonic/更快的方法是什么?

python - 逻辑运算 (Python 3.4) - 有没有办法简化长条件语句?

python - 为什么当我使用 pd.update 时 pandas 抛出 "Data overlaps."?

用于验证地址的 JavaScript 正则表达式

java - 获取元素属性值

jquery - 在 jQuery 中结合正则表达式