Chenney Huang
Chenney Huang

Reputation: 95

SyntaxError: unexpected EOF while parsing ast.literal_eval()

I'm writing a function to use the function find_key(label): to find out the count of the letters occurrence. It showed the error after I tried to convert the string into dictionary. I've checked but couldn't find a correct answer for this. Here is my code below:

import ast

def find_key(label):
    result={}
    with open('test.txt', 'r') as f:
        # print(f.readlines())
        word_list=f.readlines()[0]

        # new_list=ast.literal_eval(word_list)
        print(type(word_list))
        for word in word_list.split(','):
        # for item in word_list:
            word.strip(',{}')
            print(type(word))
            print(word)
            new_word=ast.literal_eval(word)
            print(type(new_word))
            # print(i.keys())
            if new_word.get(label):
                key=new_word.get(label)
                num=result.get(key)
                if num is not None and num >= 1:
                    result[num] = num + 1
                else:
                    result[num] = {key:1}
        print(result)




if __name__ == '__main__':
    find_key("6-15")
    # dict = {'Name': 'Zara', 'Age': 27}
    #
    # print("Value : %s" % dict.get('Age'))
    # print("Value : %s" % dict.get('Sex', "Never"))
    #
    # print(dict)

This is the format in the "text.txt" file I tried to import the data:

{'6-15':'ab'},{'9-9':'bc'},{'6-11':'cd'},{'9-9':'ef'},{'11-6':'de'},{'6-8':'fg'},{'4-15':'gh'},{'16-13':'hi'},

Here is the log when I tried to print out to check the type of the variable word_list, word and new_word:

<class 'str'>
<class 'str'>
{'6-15':'ab'}
<class 'dict'>
<class 'str'>
{'9-9':'bc'}
<class 'dict'>
<class 'str'>
{'6-11':'cd'}
<class 'dict'>
<class 'str'>
{'9-9':'ef'}
<class 'dict'>
<class 'str'>
{'11-6':'de'}
<class 'dict'>
<class 'str'>
{'6-8':'fg'}
<class 'dict'>
<class 'str'>
{'4-15':'gh'}
<class 'dict'>
<class 'str'>
{'16-13':'hi'}
<class 'dict'>
<class 'str'>

Here is the error showed after I ran the codes.

Traceback (most recent call last):
  File "/Users/chenneyhuang/PycharmProjects/freestyle/test.py", line 49, in <module>
    find_key("6-15")
  File "/Users/chenneyhuang/PycharmProjects/freestyle/test.py", line 33, in find_key
    new_word=ast.literal_eval(word)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 48, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 0

    ^
SyntaxError: unexpected EOF while parsing

I'm using Python3.6. The IDE I'm using is Pycharm. Thx.

Upvotes: 0

Views: 2403

Answers (1)

Jon Clements
Jon Clements

Reputation: 142126

You can simplify your code using next on your file-obj to get the following line (instead of .readlines()[0]) and then loop over the dictionaries returned by ast.literal_eval'ing that with a Counter so count how many values occur for each key matching your label, eg:

import ast
from collections import Counter

def find_key(label):
    with open('test.txt') as fin:
        # evaluate first line and default to empty tuple if file empty
        dicts = ast.literal_eval(next(fin, '()'))
        # Count occurrences of values for all dicts that have the label as a key
        return Counter(d[label] for d in dicts if label in d)

res = find_key('6-15')
# Counter({'ab': 1})

and:

res = find_key('9-9')
#Counter({'bc': 1, 'ef': 1})

Upvotes: 1

Related Questions