简体   繁体   English

麻烦使用AST解析的dicts

[英]Trouble using dicts parsed by AST

I have looked at all the other posts here asking the same question, but I still cannot figure out why I keep getting this Traceback. 我看过所有其他帖子,问同样的问题,但我仍然无法弄清楚为什么我一直得到这个Traceback。 The strange thing is that the program works as intended but always brings up this Traceback at the end: 奇怪的是程序按预期工作,但总是在最后调出这个Traceback:

Traceback (most recent call last):
File "/home/me/Python/NextLogAudit.py", line 5, in <module>
  i = ast.literal_eval(i)
File "/usr/lib/python3.7/ast.py", line 46, in literal_eval
  node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python3.7/ast.py", line 35, in parse
  return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1

^
SyntaxError: unexpected EOF while parsing

I am trying to figure out how to get rid of this error so the program can exit cleanly. 我试图弄清楚如何摆脱这个错误,以便程序可以干净地退出。 Also, it won't allow me to put 2 conditions in my if statement regarding the dict, so I had to nest the second condition in the first if. 另外,它不允许我在关于dict的if语句中加入2个条件,所以我必须在第一个if中嵌套第二个条件。 I'm pretty sure it has something to do with how AST is parsing the dict but cannot figure it out. 我很确定它与AST如何解析dict有关但无法弄明白。 The file I am opening is a list of dictionaries in string format: 我打开的文件是字符串格式的字典列表:

with open('/home/me/Python/logtest') as f:
for i in f.readlines():
    i = ast.literal_eval(i)
    if re.search("Preview accessed.+", i["message"]):
        if i["user"] == "user1":
            name = re.search('(?<=Preview accessed: \").+(?=\.)', \
                    i["message"])
            print("{} viewed {} on {}".format(i["user"], \
                name.group().replace('\\',''), 
                       i["time"].replace('+00:00','')))
    else:
        print("Nothing")

You need to guard against empty lines - there is one after all your data: 你需要防止空行 - 你的所有数据都有:

with open('/home/me/Python/logtest') as f:
    for i in f.readlines():
        if not i.strip():  # do nothing for empty lines
            continue
        i = ast.literal_eval(i)
        # ... rest of your code ...

Else it reads something that is not an dictionary after evaling it and you index into when using 否则,它会在评估之后读取不是字典的内容,并在使用时编入索引

i["message"]

which does not work. 这不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM