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

前端之家收集整理的这篇文章主要介绍了python – Pyparsing:如何解析数据然后编辑.txt文件中的特定值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的数据位于.txt文件中(不,我无法将其更改为其他格式),它看起来像这样:

varaiablename = value
something = thisvalue
youget = the_idea

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

  1. from pyparsing import Word,alphas,alphanums,Literal,restOfLine,OneOrMore,\
  2. empty,Suppress,replaceWith
  3.  
  4. input = open("text.txt","r")
  5. src = input.read()
  6.  
  7. # simple grammar to match #define's
  8. ident = Word(alphas + alphanums + "_")
  9. macroDef = ident.setResultsName("name") + "= " + ident.setResultsName("value") + Literal("#") + restOfLine.setResultsName("desc")
  10. for t,s,e in macroDef.scanString(src):
  11. print t.name,"=",t.value

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

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

解决方法

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

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

  1. f=open("conf.txt","r")
  2. txt=f.read() #all text is in txt
  3. f.close()
  4.  
  5. fwrite=open("modified.txt","w")
  6. splitedlines = txt.splitlines():
  7. #print splitedlines
  8. for line in splitedlines:
  9. #print line
  10. conf = line.split('=')
  11. #conf[0] is what it is on left and conf[1] is what it is on right
  12. #print conf
  13. if conf[0] == "youget":
  14. #we get this
  15. conf[1] = "the_super_idea" #the_idea is now the_super_idea
  16. #join conf whit '=' and write
  17. newline = '='.join(conf)
  18. #print newline
  19. fwrite.write(newline+"\n")
  20.  
  21. fwrite.close()

猜你在找的Python相关文章