首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SyntaxError:分析ast.literal_eval()时出现意外的EOF

SyntaxError:分析ast.literal_eval()时出现意外的EOF
EN

Stack Overflow用户
提问于 2018-08-19 16:36:43
回答 1查看 1.3K关注 0票数 0

我正在编写一个函数来使用函数find_key(label):来找出字母出现的计数。在我尝试将字符串转换为字典后,它显示了错误。我已经检查过了,但找不到正确的答案。下面是我的代码:

代码语言:javascript
运行
复制
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)

这是我试图导入数据的"text.txt“文件中的格式:

代码语言:javascript
运行
复制
{'6-15':'ab'},{'9-9':'bc'},{'6-11':'cd'},{'9-9':'ef'},{'11-6':'de'},{'6-8':'fg'},{'4-15':'gh'},{'16-13':'hi'},

以下是我尝试打印输出以检查变量word_list、word和new_word的类型时的日志:

代码语言:javascript
运行
复制
<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'>

下面是我运行代码后显示的错误。

代码语言:javascript
运行
复制
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

我使用的是Python3.6。我使用的IDE是Pycharm。谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-19 17:05:56

你可以在你的文件-obj上使用next来简化你的代码,以获得以下行(而不是.readlines()[0]),然后循环遍历ast.literal_eval'ing返回的字典,使用一个Counter来计算匹配你的标签的每个键有多少个值,例如:

代码语言:javascript
运行
复制
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})

和:

代码语言:javascript
运行
复制
res = find_key('9-9')
#Counter({'bc': 1, 'ef': 1})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51915920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档