我的数据位于.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
Run Code Online (Sandbox Code Playgroud)
那么如何告诉我的脚本编辑特定变量的特定值?
示例:
我想将variablename的值从value更改为new_value.所以基本上是变量=(我们想要编辑的数据).
我可能应该明确表示我不想直接进入文件并通过将值更改为new_value来更改值,但我想解析数据,找到变量然后给它一个新值.
即使你已经选择了另一个答案,让我回答你原来的问题,即使用pyparsing如何做到这一点.
如果您尝试在某些文本体中进行选择性更改,则transformString是比scanString更好的选择(尽管scanString或searchString可以通过查找匹配的文本来验证您的语法表达式).transformString将对您的输入字符串应用令牌抑制或解析操作修改,因为它会扫描文本以查找匹配项.
# alphas + alphanums is unnecessary, since alphanums includes all alphas
ident = Word(alphanums + "_")
# I find this shorthand form of setResultsName is a little more readable
macroDef = ident("name") + "=" + ident("value")
# define values to be updated, and their new values
valuesToUpdate = {
"variablename" : "new_value"
}
# define a parse action to apply value updates, and attach to macroDef
def updateSelectedDefinitions(tokens):
if tokens.name in valuesToUpdate:
newval = valuesToUpdate[tokens.name]
return "%s = %s" % (tokens.name, newval)
else:
raise ParseException("no update defined for this definition")
macroDef.setParseAction(updateSelectedDefinitions)
# now let transformString do all the work!
print macroDef.transformString(src)
Run Code Online (Sandbox Code Playgroud)
得到:
variablename = new_value
something = thisvalue
youget = the_idea
Run Code Online (Sandbox Code Playgroud)
对于此任务,您不需要使用特殊的实用程序或模块,您需要的是读取行并将它们拆分为列表,因此第一个索引位于左侧,第二个索引位于右侧。如果您稍后需要这些值,您可能希望将它们存储在字典中。
对于 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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1554 次 |
| 最近记录: |