用python中的字符串分割文件中的每一行
这与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)
This is concerning Python: I’m trying to figure out how to read a file line by line, separate all content on any side of an “=“ sign, and store each object in the list (of each line) into separate variables which are stored in an instance of a class: I.e. 1+3 = 4*1 = 6-2
would be a: “1+3”, b: “4*1”, c: “6-2” inside of the class dVoc. Here is what I tried, however, it seems to just be reading and printing the file as is:
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您从不调用
splitVoc
,因此它永远不会填充dVoc
。最小的修复方法就是调用它。即使您这样做了,您的代码也会产生误导(
splitVoc
是在dVoc
本身上设置类属性,而不是使用实例创建dVoc
的实例a
和b
的属性)。完整的修复(删除当前无用的所有代码)如下所示:You never call
splitVoc
, so it never populatesdVoc
. The minimal fix is to just call it.Even once you do that though, your code is misleading (
splitVoc
is setting class attributes ondVoc
itself, not making an instance ofdVoc
with instance attributes ofa
andb
). A complete fix (removing all code that's currently doing nothing useful) would look like: