将列表元素添加到字典

时间:2013-06-28 07:53:28

标签: printing dictionary syntax-error python-2.x counting

我正在尝试从文本文件中导入一个单词列表并创建一个字典,每次在循环中传递该单词时,该值都会递增。但是,使用当前的代码,没有添加,只有我添加initiall的值是在我打印字典时。我做错了什么?

import pymysql
from os import path
import re
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='db_cc')
cursor = db.cursor()
cursor.execute("SELECT id, needsprocessing, SchoolID, ClassID, TaskID FROM sharedata WHERE needsprocessing = 1")
r = cursor.fetchall()
print(r)
from os import path
import re
noentities = len(r)
a = r[0][1]
b = r[0][2]
c = r[0][3]
d = r[0][4]
filepath = "/codecompare/%s/%s/%s/%s.txt" %(a, b, c, d)
print(filepath)
foo = open(filepath, "r")
steve = foo.read()
rawimport = steve.split(' ')
dictionary = {"for":0}
foo.close()
for word in rawimport:
    if word in dictionary:
        dictionary[word] +=1
    else:
        dictionary[word] = 1
print dictionary

一些rawimport值如下:

print rawimport
['Someting', 'something', 'dangerzones', 'omething', 'ghg', 'sdf', 'hgiinsfg', '932wrtioarsjg', 'fghbyghgyug', 'sadiiilglj']

此外,当尝试从代码打印时,它会抛出

... print dictionary
  File "<stdin>", line 3
    print dictionary
        ^
SyntaxError: invalid syntax

但是,如果我单独运行打印字典,则打印:

{'for': 0}

哪个证据表明for循环没有做任何事。

有什么想法吗? 运行Python 2.7.2

编辑:更新以反映文件关闭并使循环更简单 编辑:添加样本rawimport数据

1 个答案:

答案 0 :(得分:0)

在Python解释器中进行此操作时,我收到了相同的Traceback-它是由于没有离开for循环的上下文而引起的:

>>> for word in rawimport:
...     if word in dictionary:
...             dictionary[word]+=1
...     else:
...             dictionary[word]=1
... print dictionary
  File "<stdin>", line 6
    print dictionary
        ^

解释器认为您的print语句属于for循环,并且由于未适当缩进而出错。 (当然,如果您缩进了缩进的话,它将在每次通过时打印字典)。解决该问题的方法(假设您正在解释器中执行此操作,这就是我重现您的错误的方式),请再次按回车键:

>>> for word in rawimport:
...     if word in dictionary:
...             dictionary[word]+=1
...     else:
...             dictionary[word]=1
... 
>>> print dictionary
{'for': 1, 'fghbyghgyug': 1, '932wrtioarsjg': 1, 'dangerzones': 1, 'sdf': 1, 'ghg': 1, 'Someting': 1, 'something': 1, 'omething': 1, 'sadiiilglj': 1, 'hgiinsfg': 1}
'''