本文介绍了eval to dict问题NEWB疯了!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个名为a.txt的文本文件: #comments [ (''recId'',3),(''解析'','''''''''''''''''''''''''''''''''''}'}}} [(''recId'',5),('''解析'',{''pos'':u''np'',''gen'':你是''}}) ] [(''recId'',7),('''解析'',{''pos'':u''np'',''gen'':你''' m''})] 我用它读了它: filAnsMorph = codecs.open(''a.txt'', ''r'',''utf-8'')#Initialise输入 file dicAnsMorph = {} for filAnsMorph : 如果行[0]!=''#'':#摆脱评论行 x = eval(行) dicAnsMorph [x [0] [1]] = x [1] [1] #recid是关键,解析词典是 值 但它崩溃了时间在x = eval(线)。为什么是这样?如果我将 a.txt更改为: #comments [(''recId'',3),( ''解析'',{''pos'':''''''''''''''''''''}') 它工作正常。为什么它不适用于多行?它让我开车了 疯了! 谢谢, 马修Hi,I have a text file called a.txt:# comments[(''recId'', 3), (''parse'', {''pos'': u''np'', ''gen'': u''m''})][(''recId'', 5), (''parse'', {''pos'': u''np'', ''gen'': u''m''})][(''recId'', 7 ), (''parse'', {''pos'': u''np'', ''gen'': u''m''})]I read it using this:filAnsMorph = codecs.open(''a.txt'', ''r'', ''utf-8'') # Initialise inputfiledicAnsMorph = {}for line in filAnsMorph:if line[0] != ''#'': # Get rid of comment linesx = eval(line)dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict isvalueBut it crashes every time on x = eval(line). Why is this? If I changea.txt to:# comments[(''recId'', 3), (''parse'', {''pos'': u''np'', ''gen'': u''m''})]it works fine. Why doesn''t it work with multiple lines? it''s driving mecrazy!Thanks,Matthew推荐答案 尝试: x = eval(line.strip(''\ n'')) - bruno desthuilliers python -c" print''@''。join([''。''。join([w [:: - - 1] for p in p.split(''。'')])for p in''o **** @ xiludom.gro''。split(''''')] )try with:x = eval(line.strip(''\n''))--bruno desthuillierspython -c "print ''@''.join([''.''.join([w[::-1] for w in p.split(''.'')]) forp in ''o****@xiludom.gro''.split(''@'')])" 尝试: x = eval(line.strip(''\ n'')) - bruno desthuilliers python -c" print''@''。join([''。''。join([w p.split(''。'')中的w的[:: - 1]])''o **** @ xiludom.gro'中的 p。分裂(''@ '')])"try with: x = eval(line.strip(''\n''))--bruno desthuillierspython -c "print ''@''.join([''.''.join([w[::-1] for w in p.split(''.'')]) forp in ''o****@xiludom.gro''.split(''@'')])" 是文件的最后一行空的?? 用于 for filAnsMorph中的行: #删除任何尾随和前导空格包括删除\ n line = line.strip() #删除注释行 if line.startswith(''#' '): 继续 #摆脱空行 如果行=='''': 继续 #do工作 x = eval(行) NB默认情况下strip()从目标中删除前导和尾随字符 字符串。将whitspace定义为whitespace =''\ t \ n \ x0b \ x0c \ r'' Ericis the last line of your file empty ??what withfor line in filAnsMorph:# remove any trailing and leading whitespace includes removing \nline = line.strip()# Get rid of comment linesif line.startswith(''#''):continue# Get rid of blank lineif line == '''':continue#do the jobx = eval(line)NB by default strip() removes leading and trailing characters from the targetstring. with whitspace defined as whitespace = ''\t\n\x0b\x0c\r ''Eric 这篇关于eval to dict问题NEWB疯了!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 11:10
查看更多