输入文件名作为字符串并返回字典

时间:2012-10-17 14:17:45

标签: python string dictionary filenames

我有这个功能:

def make_happiness_table("word-happiness.csv"):
   ''' make_happiness_table: string -> dict
      creates a dictionary of happiness scores from the given file '''

   return {}

但是我在尝试运行程序时遇到语法错误。

File "happiness.py", line 13
def make_happiness_table("word-happiness.csv"):
                                            ^
SyntaxError: invalid syntax

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:5)

不要在函数定义中给出实际的文件名,给出在调用函数时填充的变量,如下所示:

def make_happiness_table(filename):
   ''' make_happiness_table: string -> dict
      creates a dictionary of happiness scores from the given file '''

   return {}

make_happiness_table("word-happiness.csv")

答案 1 :(得分:3)

尝试:

def make_happiness_table(filename="word-happiness.csv"):
   ''' make_happiness_table: string -> dict
      creates a dictionary of happiness scores from the given file '''

   return {}