如何修复访问文本文件内容时的SyntaxError解析错误
修复ast.literal_eval解析时的EOF语法错误
错误原因
写入reduction.txt时,每个符合条件的排列元素末尾都添加了逗号,导致文件内容结尾多了一个无效的逗号。当读取后拼接成[{content}]格式时,这个多余的逗号会触发SyntaxError: unexpected EOF while parsing——解析器会期待逗号后还有下一个元素,但实际已到文件末尾。
另外你代码中注释掉了content.removesuffix(","),这行原本就是解决该问题的关键操作。
修复方案
方案1:优化写入逻辑(推荐)
直接收集所有符合条件的元素,一次性写入文件,彻底避免手动添加逗号的问题:
from collections import deque import numpy as np import math import yaml import sys import pickle import ast from gym import Env, spaces from gym.utils import seeding from envs.core_v2 import BS, UE from itertools import permutations,product,combinations, compress from envs.utils import get_len_space, relaxed_to_one_hot, to_categorical with open("reduction.txt", "w") as file: no_actions = 0 UEs = [[1,2,3],[4,5,6]] List_UE = [list(p) for p in product(*UEs)] comb = permutations(List_UE, 3) valid_actions = [] for i in comb: unique_elements, counts= np.unique(list(i), return_counts=True) if all(counts == 1): no_actions += 1 valid_actions.append(list(i)) # 直接将整个列表转为字符串写入,自动处理逗号分隔 file.write(str(valid_actions))
方案2:修复读取逻辑
如果不想修改写入代码,就在读取时移除末尾的多余逗号,确保语法合法:
from collections import deque import numpy as np import math import yaml import sys import pickle import ast from gym import Env, spaces from gym.utils import seeding from envs.core_v2 import BS, UE from itertools import permutations,product,combinations, compress from envs.utils import get_len_space, relaxed_to_one_hot, to_categorical with open("reduction.txt", 'r') as file: content = file.read().strip() # 移除末尾的逗号(如果存在) if content.endswith(','): content = content[:-1] # Python 3.9+ 也可以用 content = content.removesuffix(',') action_list = ast.literal_eval(f'[{content}]') action = action_list[action_index]
额外优化点
permutations本身生成的就是不重复元素的排列,你代码中的np.unique判断逻辑其实多余,可以直接移除来提升效率:
# 替换原判断代码 # unique_elements, counts= np.unique(list(i), return_counts=True) # if all(counts == 1): if True: no_actions += 1 valid_actions.append(list(i))
内容的提问来源于stack exchange,提问作者Salwa Mostafa
相关产品推荐
相关产品推荐

