首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用python中的字符串分隔文件中的每一行

用python中的字符串分隔文件中的每一行
EN

Stack Overflow用户
提问于 2022-03-17 19:06:29
回答 1查看 229关注 0票数 -2

这是关于Python的:我试图弄清楚如何逐行读取文件,将“=”符号的任何一侧的所有内容分开,并将列表中的每个对象(每一行)存储到单独的变量中,这些变量存储在类的实例中:即1+3 = 4*1 = 6-2将是a:“1+3”,b:“4*1”,c:“6-2”在类dVoc中。下面是我尝试过的,但是,它似乎只是读取和打印文件如下:

代码语言:javascript
运行
复制
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)

EN

回答 1

Stack Overflow用户

发布于 2022-03-17 19:14:18

您从不调用splitVoc,因此它从不填充dVoc。最起码的解决办法就是叫它。

即使这样做了,您的代码也会产生误导(splitVoc是在dVoc本身上设置类属性,而不是使用ab的实例属性来创建dVoc实例)。一个完整的修复程序(删除当前没有任何有用功能的所有代码)如下所示:

代码语言:javascript
运行
复制
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)  
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71517764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档