正如@LhasaDad 之前的评论中提到的。
我在您所附的代码中观察到两个错误。
第一个错误:
首先是“def”声明。该函数需要一个变量占位符而不是变量的值。例如:
>>> def fun('hello'):
File "<stdin>", line 1
def fun('hello'):
^
SyntaxError: invalid syntax
>>> def fun(5):
File "<stdin>", line 1
def fun(5):
^
SyntaxError: invalid syntax
正确的方法是
>>> def fun(var):
... print(var)
...
>>> #Then call the function using below method
...
>>> fun('hello')
hello
>>> fun(5)
5
第二个错误:
应该始终有缩进(def 语句后有制表符或 4 个空格)
所以在你的情况下希望这会起作用
def DataExtract(file_path):
fp = open(file_path)
data = {}
line = fp.read().split("\n")[2:7:5]
while line:
name, _, cont = line.partition(":")
keys, _, values = cont.partition("=")
keys = keys.split(",")
values = values.split(",")
temp_d = {}
for i in range(len(keys)):
key = keys[i].strip()
val = values[i].strip()
temp_d[key] = float(val)
data[name] = temp_d
line = fp.readline()
fp.close()
# Now call the function as
DataExtract('C:/Users/username/Desktop/d.txt')
您还可以从 def 阅读如何使用 python 函数https://www.w3schools.com/python/python_functions.asp https://www.w3schools.com/python/python_functions.asp