我正在编写一个使用函数find_key(label)
的函数:找出字母出现的次数。我尝试将字符串转换为字典后显示错误。我已经检查过,但找不到正确的答案。这是我的代码如下:
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”文件中的格式:
{'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的类型时的日志:
<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'>
这是我运行代码后显示的错误。
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。谢谢。
答案 0 :(得分:0)
您可以在文件obj上使用next
来简化代码,以获取下一行(而不是.readlines()[0]
),然后循环遍历ast.literal_eval
返回的字典,并用Counter
,因此请计算与标签匹配的每个键有多少个值,例如:
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})
和:
res = find_key('9-9')
#Counter({'bc': 1, 'ef': 1})