我正在尝试获取从文本文件导入的单词列表,并创建一个字典,每次在循环中传递该单词时,字典中的值都会递增。但是,使用我当前拥有的代码,在打印字典时,没有添加任何内容,只有我添加的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数据
发布于 2019-06-18 08:16:28
当我在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
^解释器认为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}
'''https://stackoverflow.com/questions/17359875
复制相似问题