-1

割り当て: 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()

出力ファイルの何も置き換えません。ヘルプ!

4

2 に答える 2

2

問題は、一致が見つかった場合、コードが置換文字列を行末に貼り付けるだけであることです。

if userStr in words:
   output_data.write(line + userReplace)  # <-- Right here
else:
   output_data.write(line)

を使用できないため.replace()、回避する必要があります。その単語があなたの行のどこにあるかを見つけて、その部分を切り取り、userReplaceその場所に貼り付けます.

これを行うには、次のようなことを試してください。

for line in input_data:
   while userStr in line:
      index = line.index(userStr)  # The place where `userStr` occurs in `line`.

      # You need to cut `line` into two parts: the part before `index` and
      # the part after `index`. Remember to consider in the length of `userStr`.

      line = part_before_index + userReplace + part_after_index

   output_data.write(line + '\n')  # You still need to add a newline 

回避するためのもう少し厄介な方法replaceは、を使用することre.sub()です。

于 2012-10-02T03:39:50.833 に答える
1

と を使用splitjoinて実装できますreplace

output_data.write(userReplace.join(line.split(userStr)))
于 2012-10-02T03:56:45.240 に答える