Skip to main content
 首页 » 编程设计

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

2025年05月04日20jpfss

我有这个功能:

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 

我该如何解决这个问题?

请您参考如下方法:

不要在你的函数定义中给出一个实际的文件名,给出一个在函数被调用时填充的变量,就像这样:

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