割り当て: X と Y を 2 つの単語とします。検索/置換は、特定のドキュメント内で出現する単語 X を検索し、それを単語 Y に置き換える一般的なワード プロセッシング操作です。
あなたの仕事は、検索/置換操作を実行するプログラムを作成することです。プログラムは、置換する単語 (X)、次に置換単語 (Y) をユーザーに要求します。入力ドキュメントの名前が input.txt であるとします。この検索/置換操作の結果を output.txt という名前のファイルに書き込む必要があります。最後に、Python に組み込まれている replace() 文字列関数を使用することはできません (割り当てが非常に簡単になります)。
コードをテストするには、メモ帳や IDLE などのテキスト エディターを使用して input.txt を変更し、さまざまなテキスト行を含める必要があります。繰り返しますが、コードの出力はサンプル出力とまったく同じでなければなりません。
これは私のコードです:
input_data = open('input.txt','r') #this opens the file to read it.
output_data = open('output.txt','w') #this opens a file to write to.
userStr= (raw_input('Enter the word to be replaced:')) #this prompts the user for a word
userReplace =(raw_input('What should I replace all occurences of ' + userStr + ' with?')) #this prompts the user for the replacement word
for line in input_data:
words = line.split()
if userStr in words:
output_data.write(line + userReplace)
else:
output_data.write(line)
print 'All occurences of '+userStr+' in input.txt have been replaced by '+userReplace+' in output.txt' #this tells the user that we have replaced the words they gave us
input_data.close() #this closes the documents we opened before
output_data.close()
出力ファイルの何も置き換えません。ヘルプ!