AttributeError:'list'对象没有属性'keys'

时间:2016-06-22 07:23:26

标签: python nlp text-mining

我尝试计算字频并将频率从大到小排序 但面对上面的列表对象没有属性键问题

我认为结果真的是一个决定因素,它怎么能没有“关键”? 感谢。

#encoding=utf-8
import os


result = {}
if os.path.exists("test.txt"):
    day_file = open("test.txt").read()
    day_file_list = day_file.split(" ")

    for i in day_file_list:
                #   print "i: s" + str(i) + "e"
        if i == "#" or " ":
            day_file_list.remove(i)
                        #continue
            if i not in result:
                result[i] = 1  
            else:
                result[i] = result[i] + 1
                #   print "result i: " + str(result[i])

result = sorted(result.items(), key = lambda item: item[1], reverse=True)


for k in result.keys():
    print result[k]

1 个答案:

答案 0 :(得分:2)

内置函数result = sorted(result.items(), key = lambda item: item[1], reverse=True) # result is now a list, check it with "print type(result)" for k in result.keys(): # trying to access list's keys, which is not a thing 将iterable作为参数并返回列表

你需要进一步转换才能获得一个dict,它具有属性sorted(result.items())以避免该异常

result = sorted..

但把它变成一个词典并不是你想要的。相反,由于for i in result: print i 以排序顺序成为dict项目列表,因此您无需遍历dict的键来获取项目。在public function onKernelException(GetResponseForExceptionEvent $event) { // You get the exception object from the received event $exception = $event->getException(); if('Some\Namespace\ApiException' == get_class($exception)){ $res = new JsonResponse([ 'message'=>$exception->getMessage(), ], 500); $event->setResponse($res); } } 行后执行类似的操作:

if (wsObject.getFoo() != null && wsObject.getFoo().getBar() != null && wsObject.getFoo().getBar().getBaz() != null) 
   return wsObject.getFoo().getBar().getBaz().getInt();
else
   return something or throw exception;