如何读取txt文件中的数组?

时间:2019-06-20 14:59:35

标签: python split readline

我需要从.txt文件中读取以下行:

Turn  60 Player  -1
board: [[ 0  0  0  0  1  2  0  6 12  0  1  0  0  5  5 21]]
action p-values: [0.0, 0.0, 0.0, 0.0, 0.6326530612244898, 0.3673469387755102, 0.0]
nn: legal moves:[4, 5]
nn: select: 4
nn: db_lookup  0 0 0 0 1 2 0 6 12 0 1 0
nn: scores: [127, 127, 127, 127, -4, -5]
nn: best move selected

如何提取数组动作p值中的数字?

我需要创建相同的数组。

这是我的出发点:

with open(match, 'r') as searchfile:
        for line in searchfile:
            if 'Turn' in line:
                line = next(searchfile)
                line = next(searchfile)
                if 'p-values' in line:
                    line.rstrip('\n')
                    fields = line.split(": ")
                    pvalues.append(fields[1])

但是,如果我尝试打印pvalues,则会得到一个带有字符串(包含\ n在内)的数组。我该如何在pvalues和array中使用float的内部数组?

谢谢

3 个答案:

答案 0 :(得分:2)

您可以使用ast库将字符串转换为列表,并且rstrip中存在错误。见下文。

import ast
pvalues=[]
with open('match', 'r') as searchfile:
        for line in searchfile:
            if 'Turn' in line:
                line = next(searchfile)
                line = next(searchfile)
                if 'p-values' in line:
                    line=line.rstrip('\n')
                    fields = line.split(": ")
                    pvalues.append(ast.literal_eval(fields[1]))
pvalues

Result:
[[0.0, 0.0, 0.0, 0.0, 0.6326530612244898, 0.3673469387755102, 0.0]]

答案 1 :(得分:1)

您可以首先根据service_port进行拆分,然后剥去换行符:,然后使用\n将字符串转换为列表

literal_eval

答案 2 :(得分:0)

通过re.findall功能准确地实现:

import re

with open('file.txt') as f:
    pvalues = []
    pat = re.compile(r'\d+\.?\d+')
    for line in f:
        if 'Turn' in line:
            next(f)
            line = next(f)
            if 'p-values' in line:
                num_str = line.strip().split(": ")[1]
                pvalues.append(list(map(float, pat.findall(num_str))))

print(pvalues)

输出(带有浮点数的列表的列表):

[[0.0, 0.0, 0.0, 0.0, 0.6326530612244898, 0.3673469387755102, 0.0]]