以字符串形式输入文件名并返回字典

2024-04-20 05:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我的职责是:

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

我怎样才能解决这个问题?你知道吗


Tags: ofcsvthefromstringmakedictionarydef
2条回答

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

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")

尝试:

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

   return {}

相关问题 更多 >