我正在尝试获取从文本文件中导入的单词列表并制作一个字典,其中每次在循环中传递单词时值都会递增。但是,使用我拥有的当前代码,没有添加任何内容,并且当我打印字典时只有我添加的初始值存在。我究竟做错了什么?
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 数据