加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Pyparsing:如何解析数据然后编辑.txt文件中的特定值

发布时间:2020-12-16 23:19:31 所属栏目:Python 来源:网络整理
导读:我的数据位于.txt文件中(不,我无法将其更改为其他格式),它看起来像这样: varaiablename = value something = thisvalue youget = the_idea 这是我到目前为止的代码(取自Pyparsing中的示例): from pyparsing import Word,alphas,alphanums,Literal,restOfLi
我的数据位于.txt文件中(不,我无法将其更改为其他格式),它看起来像这样:

varaiablename = value
something = thisvalue
youget = the_idea

这是我到目前为止的代码(取自Pyparsing中的示例):

from pyparsing import Word,alphas,alphanums,Literal,restOfLine,OneOrMore,
empty,Suppress,replaceWith

input = open("text.txt","r")
src = input.read()

# simple grammar to match #define's
ident = Word(alphas + alphanums + "_")
macroDef = ident.setResultsName("name") + "= " + ident.setResultsName("value") + Literal("#") + restOfLine.setResultsName("desc")
for t,s,e in macroDef.scanString(src):
print t.name,"=",t.value

那么如何告诉我的脚本编辑特定变量的特定值?
例:
我想将variablename的值从value更改为new_value.
所以基本上是变量=(我们想要编辑的数据).

我可能应该明确表示我不想直接进入文件并通过将值更改为new_value来更改值,但我想解析数据,找到变量然后给它一个新值.

解决方法

对于此任务,您不需要使用特殊实用程序或模块
你需要的是读取行并将它们分成列表,所以第一个索引是左边,第二个索引是右边.
如果以后需要这些值,可能需要将它们存储在字典中.

那么这里是简单的方法,对于python中的新人.取消注释行白色打印以将其用作调试.

f=open("conf.txt","r")
txt=f.read() #all text is in txt
f.close()

fwrite=open("modified.txt","w")
splitedlines = txt.splitlines():
#print splitedlines 
for line in splitedlines:
    #print line
    conf = line.split('=')
    #conf[0] is what it is on left and conf[1] is what it is on right
    #print conf
    if conf[0] == "youget":
        #we get this
        conf[1] = "the_super_idea" #the_idea is now the_super_idea
    #join conf whit '=' and write
    newline = '='.join(conf)
    #print newline
    fwrite.write(newline+"n")

fwrite.close()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读