我是OOP新手,我一直在尝试编写一个可以导入的类,它将帮助我解析文件。我意识到我不需要制作一个类来做这件事,但我想我会尝试这样做,这样我就可以开始熟悉OOP了
此代码有效
import re
import os
destdir = r"FilePathToDirectory"
class Parsey():
def GetNums(self,source, destination, trim = True):
with open (os.path.join(destdir,source), 'r') as infile:
with open (os.path.join(destdir,destination), 'w') as outfile:
for line in infile:
#Look for number patern match
if re.match(r'(.*)\d\d-\d\d-\d\d\d\d(.*)', line):
#If trim is True clean up the line
if trim == True:
#Find the first numeric character
firstdig = re.search("\d",line)
#Set the firstdig variable to the integer of that index
firstdig = firstdig.start()
#Set the line equal to only the begining and ending indexes of the number
line=line[firstdig:firstdig+10]
#Remove the dashes from the string
line = line.replace('-','')
outfile.writelines(line+'\n')
else:
outfile.writelines(line)
这段代码没有,我不知道为什么没有
import re
import os
class Parsey():
def __init__(self, destdir=''):
self.destdir = r"FilePathToDirectory"
def GetNums(self,source, destination, trim = True):
with open (os.path.join(destdir,source), 'r') as infile:
with open (os.path.join(destdir,destination), 'w') as outfile:
for line in infile:
#Look for number patern match
if re.match(r'(.*)\d\d-\d\d-\d\d\d\d(.*)', line):
#If trim is True clean up the line
if trim == True:
#Find the first numeric character
firstdig = re.search("\d",line)
#Set the firstdig variable to the integer of that index
firstdig = firstdig.start()
#Set the line equal to only the begining and ending indexes of the number
line=line[firstdig:firstdig+11]
#Remove the dashes from the string
line = line.replace('-','')
outfile.writelines(line+'\n')
else:
outfile.writelines(line)
我收到错误消息: 第10行,在GetNums中 使用open(os.path.join(destdir,source),'r')作为内嵌: NameError:未定义名称“destdir”
我的理解是,类对象的名称空间将允许类中的函数查看该类中声明的所有变量
您需要将第10行更改为:
在您的例子中,Python首先在
GetNums
中查找testdir
,如果在那里找不到,它将在模块中查找该名称。它不会神奇地使用来自__init__
的tesdir
。名称self
代表稍后创建的实例。因此,在__init__
中,您基本上设置了mysinstance.testdir
,稍后在GetNums
中,您可以使用mysinstance.testdir
进行访问self
只是mysinstance
的占位符,即稍后创建的实例您可以在documentation中阅读详细信息
@Mike Müller搞定了,但下面是完整的更正代码
相关问题 更多 >
编程相关推荐