Python 我得到一个错误,说小写的_行没有定义
问题在于Python 我得到一个错误,说小写的_行没有定义,python,Python,问题在于小写字母_line是normalize函数的一个局部变量,您在调用该函数时没有保存其返回变量 只需放置lowercase\u line=normalize(filename)此函数中定义了lowercase\u line的唯一位置: import string def getData(filename): with open(filename,'r') as f: lines=[line.rstrip() for line in f] lines=[x.lower(
小写字母_line
是normalize
函数的一个局部变量,您在调用该函数时没有保存其返回变量
只需放置
lowercase\u line=normalize(filename)
此函数中定义了lowercase\u line
的唯一位置:
import string
def getData(filename):
with open(filename,'r') as f:
lines=[line.rstrip() for line in f]
lines=[x.lower() for x in lines]
return lines
filename="bibleSentences.txt"
getData(filename)
def normalize(filename):
lowercase_lines=[x.lower() for x in getData(filename)]
return lowercase_lines
normalize(filename)
def replace_all(text,dic):
for p in normalize(filename):
for i,j in dic.iteritems():
text=text.replace(i,j)
print (text)
return text
text=lowercase_lines
dic={"and":"","the" :"", "in":"", "it":"", "was":"", "his":"", "of":"", "so":"" }
print(replace_all(normalize))
但是这个变量在所谓的“函数范围”中,这意味着它只在函数存在之前存在。您需要捕获从函数返回的值,以便在函数外部使用它。但实际上,你是在这样做:
def normalize(filename):
lowercase_lines=[x.lower() for x in getData(filename)]
return lowercase_lines
for p in normalize(filename):
我看不出这行有什么价值:
def normalize(filename):
lowercase_lines=[x.lower() for x in getData(filename)]
return lowercase_lines
for p in normalize(filename):
我给你准备好了。您已经在使用上面的normalize()函数的结果。我认为删除这一行是您想要做的,除非下面还有其他代码使用值
text
您的函数都返回值,但您需要将它们设置为变量:
text=lowercase_lines
等等。这是规格化功能的本地设置。您不能在函数外部直接访问它。您正在调用normalize,但随后放弃返回值-将其保存在该变量中。(希望语法是显而易见的——我现在不能像在手机上写这篇文章那样轻易地发布任何代码。)