我正在尝试用英语单词(有点像翻译)替换文本文件中的单词。但是,出现错误 builtins.NameError:未定义名称'contents'。如果您需要知道,文本文件是一个字符串列表(中文),用逗号分隔(我需要用英文字符串替换)。
def translate():
contents = ""
deleteWords = ["hop", "job"]
replaceWords = {"T波改变": "T-wave", "窦性心律不齐":"sinus arrhythmia"}
with open("sample.txt") as diagnosis:
contents = diagnosis.read()
for key, value in replaceWords.iteritems():
contents = contents.replace(key, value)
return contents
print(contents)
答案 0 :(得分:2)
您在函数内部声明了function toogleView(){
$('.menu-toggle').click(function(){
$('.menu-toggle').trigger('active');
$('nav').trigger('active');
});
}
,因此它的作用域是此函数,不能在函数外部访问。
尝试:用contents
代替print(translate())
答案 1 :(得分:1)
contents
是一个私有变量,仅在函数内部可用,并在函数完成后立即回收。您需要调用该函数并保存其值。
def translate():
contents = ""
#deleteWords = ["hop", "job"] # This variable is unused so commented out. Delete this line
replaceWords = {"T波改变": "T-wave", "窦性心律不齐":"sinus arrhythmia"}
with open("sample.txt") as diagnosis:
contents = diagnosis.read()
for key, value in replaceWords.iteritems():
contents = contents.replace(key, value)
return contents
# Here contents is a different variable with the same value
contents = translate() # <== Added this line to make it work
print(contents)