1

この「これはステートメントです」のような文字列があり、文字列を検索してこれに置き換えたい場合は、「この**ステートメント」としましょう

検索する文字列 this is a statement 、this si a statement 、this ia statement 、および任意の組み合わせ これらをこのtrim a ステートメントに変換します。つまり、this と a ステートメントの間の任意の単語の組み合わせ を別のセットのtrimに置き換えます funnotfunに置き換えます。

これがプログラムです

import re
file=open('file','r+')
search=re.sub('this \(a_zA_Z0_9)+ a statement','\1trim',file),('this is fun','this is notfun',file)
file.close()

ファイルで何も変更されていないため、何かが正しくありません。

みんな、ありがとう。

4

1 に答える 1

1

re.subファイルでは機能せず、文字列で機能します。ファイルの内容を文字列に読み取り、 re.sub を使用して文字列を変更し、変更された文字列をファイルに書き戻す必要があります。

簡単な例:

text = open("myfile.txt").read()
# This is your original re.sub call, but I'm not sure it really does what you want.
text = re.sub('this \(a_zA_Z0_9)+ a statement', '\1trim', text)
text = re.sub('this \(a_zA_Z0_9)+ another replacement', 'some other thing', text)
open("myfile.txt", "w").write(text)
于 2009-12-22T01:10:04.287 に答える