6

私のデータは .txt ファイルにあり (いいえ、別の形式に変更することはできません)、次のようになります。

変数名 = 値
何か = この値
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 に変更して値を変更したくないことを明確にする必要がありますが、データを解析し、変数を見つけてから新しい値を与えたいと考えています。

4

4 に答える 4

6

すでに別の回答を選択されていますが、pyparsing を使用してこれを行う方法である元の質問に答えさせてください。

テキストの一部を選択的に変更しようとしている場合は、scanString よりも transformString を選択することをお勧めします (ただし、一致するテキストを探して文法式を検証するには、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

このタスクでは、特別なユーティリティやモジュールを使用する必要はありません。必要なのは、行を読み取り、それらをリストに分割することです。したがって、最初のインデックスは左側にあり、2 番目のインデックスは右側にあります。後でこれらの値が必要になった場合は、それらをディクショナリに保存することをお勧めします。

さて、これは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

ConfigParser

import ConfigParser

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

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

ただし、ヘッダーがない場合は怒鳴られますが[section]、大丈夫です。ヘッダーを偽造できます

于 2010-12-20T22:05:53.750 に答える
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 に答える