6

我的数据位于 .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

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

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

4

4 回答 4

6

即使您已经选择了另一个答案,让我回答您最初的问题,即如何使用 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)

给出:

variablename = new_value
something = thisvalue
youget = the_idea
于 2010-12-21T10:26:18.247 回答
3

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

好吧,对于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()
于 2010-12-20T22:07:25.610 回答
1

实际上,您应该看一下config parser 模块, 它可以准确地解析您的语法(您只需要在开头添加 [section] )。

如果你坚持你的实现,你可以创建一个字典:

dictt = {}
for t,s,e in macroDef.scanString(src):
   dictt[t.name]= t.value
dictt[variable]=new_value
于 2010-12-20T22:00:40.283 回答
1

配置解析器

import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('example.txt')

variablename = config.get('variablename', 'float')

但是,如果您没有[section]标头,它会对您大喊大叫,但是没关系,您可以伪造一个

于 2010-12-20T22:05:53.750 回答