这是关于Python的:我试图弄清楚如何逐行读取文件,将“=”符号的任何一侧的所有内容分开,并将列表中的每个对象(每一行)存储到单独的变量中,这些变量存储在类的实例中:即1+3 = 4*1 = 6-2
将是a:“1+3”,b:“4*1”,c:“6-2”在类dVoc中。下面是我尝试过的,但是,它似乎只是读取和打印文件如下:
import getVoc
class dVoc:
def __init__(self, a, b):
self.a = a
self.b = b
def splitVoc():
with open("d1.md","r") as d1r:
outfile = open(f,'r')
data = d1r.readlines()
out_file.close()
def_ab = [line.split("=") for line in data]
def_ab
dVoc.a = def_ab[0]
dVoc.b = def_ab[-1]
print(dVoc.a)
发布于 2022-03-17 19:14:18
您从不调用splitVoc
,因此它从不填充dVoc
。最起码的解决办法就是叫它。
即使这样做了,您的代码也会产生误导(splitVoc
是在dVoc
本身上设置类属性,而不是使用a
和b
的实例属性来创建dVoc
实例)。一个完整的修复程序(删除当前没有任何有用功能的所有代码)如下所示:
class dVoc:
def __init__(self, a, b):
self.a = a
self.b = b
def splitVoc():
with open("d1.md","r") as d1r:
# d1r is already an iterable of lines, no need to call .readlines()
# just to iterate it and discard it
def_ab = [line.split("=") for line in d1r]
# Uses the list produced from splitting the first and last lines
# only; make sure that's the intent
return dVoc(def_ab[0], def_ab[-1])
voc = splitVoc()
# Thanks to only using a, this is equivalent to reading one line from the file,
# splitting it on '=', and ignoring the entire rest of the file
print(voc.a)
https://stackoverflow.com/questions/71517764
复制相似问题