[英]Split each line in a file with a string in python
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: Ie 1+3 = 4*1 = 6-2
would be a: “1+3”, b: “4*1”, c: “6-2” inside of the class dVoc.这是关于 Python 的:我试图弄清楚如何逐行读取文件,将所有内容分隔在“=”符号的任何一侧,并将列表(每行)中的每个 object 存储到单独的变量中存储在a class的实例中:即1+3 = 4*1 = 6-2
将是a:“1+3”,b:“4*1”,c:class内的“6-2” 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)
You never call splitVoc
, so it never populates dVoc
.您永远不会调用splitVoc
,因此它永远不会填充dVoc
。 The minimal fix is to just call it.最小的修复方法是调用它。
Even once you do that though, your code is misleading ( splitVoc
is setting class attributes on dVoc
itself, not making an instance of dVoc
with instance attributes of a
and b
).即使你这样做了,你的代码也会产生误导( splitVoc
是在dVoc
本身上设置 class 属性,而不是使用a
和b
的实例属性dVoc
的实例)。 A complete fix (removing all code that's currently doing nothing useful) would look like:一个完整的修复(删除所有当前无用的代码)看起来像:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.