Printing 向字典添加列表元素

Printing 向字典添加列表元素,printing,dictionary,syntax-error,python-2.x,counting,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()

我试图获取从文本文件导入的单词列表,并制作一个字典,每次在循环中传递单词时,该值都会递增。然而,对于我现有的代码,没有添加任何代码,当我打印字典时,只有我添加的值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
一些RAW导入值如下所示:

print rawimport
['Someting', 'something', 'dangerzones', 'omething', 'ghg', 'sdf', 'hgiinsfg', '932wrtioarsjg', 'fghbyghgyug', 'sadiiilglj']
此外,当试图从代码中打印时,它会抛出

... print dictionary
  File "<stdin>", line 3
    print dictionary
        ^
SyntaxError: invalid syntax
这就是for-loop什么都没做的证据

有什么想法吗? 运行Python 2.7.2

编辑:更新以反映文件关闭并简化循环
编辑:添加了示例rawimport数据

在Python解释器中处理此问题时,我收到了相同的回溯——这是因为没有离开for循环的上下文:

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

在for循环中,为什么不执行
else:dictionary[word]=1
而不是赋值0然后添加1?你能举一个例子说明rawimport的内容吗。你没有关闭foo。我已经关闭foo,改为你给出的行,问题仍然存在。我将在问题中添加rawimport的示例。谢谢你的帮助,汤姆
>>> for word in rawimport:
...     if word in dictionary:
...             dictionary[word]+=1
...     else:
...             dictionary[word]=1
... print dictionary
  File "<stdin>", line 6
    print dictionary
        ^
>>> 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}
'''