Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用不同的单词替换文本文件中的单词(python)_Python_Replace - Fatal编程技术网

用不同的单词替换文本文件中的单词(python)

用不同的单词替换文本文件中的单词(python),python,replace,Python,Replace,我试图用英语单词替换文本文件中的单词(有点像译者)。但是,我得到的错误是内置的。NameError:没有定义名称“contents”。如果您需要知道,textfile是一个字符串列表(中文),用逗号分隔(我需要用英文字符串替换) 内容是一个私有变量,仅在函数内部可用,函数完成后可立即循环使用。您需要调用函数并保存其值 def translate(): contents = "" #deleteWords = ["hop", "job"] # This variable is u

我试图用英语单词替换文本文件中的单词(有点像译者)。但是,我得到的错误是内置的。NameError:没有定义名称“contents”。如果您需要知道,textfile是一个字符串列表(中文),用逗号分隔(我需要用英文字符串替换)


内容
是一个私有变量,仅在函数内部可用,函数完成后可立即循环使用。您需要调用函数并保存其值

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)
def translate():
contents=“”
#deleteWords=[“hop”,“job”]#此变量未使用,因此被注释掉。删除这一行
replaceWords={“T波改变": "T波“窦性心律不齐":"窦性心律失常“}
打开(“sample.txt”)作为诊断:
内容=诊断。读取()
对于键,replaceWords.iteritems()中的值:
contents=contents.replace(键,值)
返回内容
#这里的内容是具有相同值的不同变量

contents=translate()#您在函数内部声明
contents
,因此它的作用域是此函数,不能在函数外部访问


尝试:
print(translate())
而不是
print(contents)

contents=translate()
是添加到代码中的调用。这就是所需的更改
名称错误
是因为您引用的变量是在函数范围内创建的,但它不存在于该函数之外。尝试
print(translate())
我得到了错误:对于键,replaceWord中的值。iteritems():builtins.AttributeError:'dict'对象没有属性'iteritems'Try'items',而不是'iteritems'iteritems’用于较旧版本的Python中。
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)