python中的脚本:未定义模板

时间:2016-02-29 23:09:36

标签: python

我正在使用以下Python脚本:

import numpy as np
import matplotlib.pyplot as plt
import nibabel
import os

def collapse_probtrack_results(waytotal_file, matrix_file):
    with open(waytotal_file) as f:
        waytotal = int(f.read())
    data = nibabel.load(matrix_file).get_data()
    collapsed = data.sum(axis=0) / waytotal * 100.
    return collapsed

matrix_template = 'results/{roi}.nii.gz.probtrackx2/matrix_seeds_to_all_targets.nii.gz'
processed_seed_list = [s.replace('.nii.gz','').replace('label/', '')
    for s in open('/home/salvatore/tirocinio/aal_rois_diff_space/aal.txt').read().split('\n')
    if s]
N = len(processed_seed_list)
conn = np.zeros((N, N))
rois=[]
idx = 0
for roi in processed_seed_list:
    matrix_file = template.format(roi=roi)
    seed_directory = os.path.dirname(result)
    roi = os.path.basename(seed_directory).replace('.nii.gz.probtrackx2', '')
    waytotal_file = os.path.join(seed_directory, 'waytotal')
    rois.append(roi)
    try:
        # if this particular seed hasn't finished processing, you can still
        # build the matrix by catching OSErrors that pop up from trying
        # to open the non-existent files
        conn[idx, :] = collapse_probtrack_results(waytotal_file, matrix_file)
    except OSError:
        pass
    idx += 1

# figure plotting
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(conn, interpolation='nearest', )
cax.set_cmap('hot')
caxes = cax.get_axes()

当我尝试运行它时,我收到以下错误:NameError:name' template'没有定义。这是指上面脚本的第22行。你能帮我弄清楚这是什么意思吗?

1 个答案:

答案 0 :(得分:0)

没有像template这样的变量,因此template不能在表达式的右侧使用。尝试

    matrix_file = matrix_template.format(roi=roi)

代替。