出于某种原因,我的open语句中出现语法错误:
def printStatsToFile():
global dictionary
statslines = []
if dictionary=={}:
createDictionary()
for n in dictionary:
statslines.append("Key = " + str(n) + " Total number of words with " + str(n) + " characters = " + str(len(dictionary[n]))
open(statsWords.dat, "w").writelines(statslines)
print "Your stats are now available in statsWords.dat."
mainFunction()
这是错误:
tog:hw4 lukasolson$ python hw4_lukasolson.py
File "hw4_lukasolson.py", line 61
open(statsWords.dat, "w").writelines(statslines)
^
SyntaxError: invalid syntax
奇怪的是,当我注释掉部分代码时,一切都运行得很好:
def printStatsToFile():
statslines = []
"""
global dictionary
if dictionary=={}:
createDictionary()
for n in dictionary:
statslines.append("Key = " + str(n) + " Total number of words with " + str(n) + " characters = " + str(len(dictionary[n]))
"""
open("statsWords.dat", "w").writelines(statslines)
print "Your stats are now available in statsWords.dat."
mainFunction()
我正在运行python 2.7.6,据我所知,我的语法应该是正确的。
tog:hw4 lukasolson$ python
Python 2.7.6rc1 (v2.7.6rc1:4913d0e9be30+, Oct 27 2013, 20:52:11)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
答案 0 :(得分:4)
你在它上面的一行上错过了一个右括号。
答案 1 :(得分:0)
您需要将statsWords.dat
作为字符串传递。因此,该行应如下所示:
open("statsWords.dat", "w").writelines(statslines)