2016-12-07 9 views
0

ディレクトリ(file1.txt、file2.txt、...)に多数のファイルがあり、その単語が後で来るのを見つけて置き換えたいと思います。複数のファイルの次の単語を検索して置き換えます

directory = os.listdir('/Users/user/My Documents/test/') 
os.chdir('/Users/user/My Documents/test/') 
for file in directory: 
    open_file = open(file,'r') 
    read_file = open_file.readlines() 
    next_word = read_file[read_file.index('not')+1] 
    print(next_word) 
    replace_word = replace_word. replace(next_word ,' ') 

私は

next_word = read_file[read_file.index('not')+1] 
ValueError: 'not' is not in list 

任意のアイデアをエラーことができ!!!!!!

+0

'read_file'は、行のリストです単一の文字列ではありません。 –

答えて

0

read_fileは、文字列のリストではなく、単一の文字列であるため、このエラーを取得しています。 indexメソッドがlistの場合、ファイル内の行がまったく "not"であるため、表示されているエラーが発生します。文字列のindexメソッドもエラーを発生させますが、findは-1を返します。

あなたは、あなたのテストのために回線を介してループする必要があります。

os.chdir('/Users/user/My Documents/test/') 
directory = os.listdir('.') 
for file in directory: 
    with open(file, 'r') as open_file: 
     read_file = open_file.readlines() 

    previous_word = None 
    output_lines = [] 
    for line in read_file: 
     words = line.split() 
     output_line = [] 
     for word in words: 
      if previous_word != 'not': 
       output_line.append(word) 
      else: 
       print('Removing', word) 
      previous_word = word 
     output_lines.append(' '.join(output_line)) 

あなたが彼らと一緒に行われたときに、ファイルを閉じることが重要であるので、私は終了しますwithブロックにopenコールを追加しましたエラーがあっても、あなたのためのファイル。

実際の置換/削除は、最初に行を単語に分割し、その後に続く単語を別のバッファに追加することで機能します('not')。行が終了すると、スペースで1つの文字列に結合され、出力行リストに追加されます。

Noneは、外側のforループの前に、各行ではなく1回だけ初期化されていることに注意してください。これにより、'not'で終わる行は、次の行の最初の単語に置換されます。

あなたは、元のファイルに処理されたファイルを書き込むファイルリストの上に、最も外側のforループの最後に次のコードを追加したい場合は、次の

with open(file, 'w') as open_file: 
    open_file.write('\n'.join(output_lines)) 
0

単語「not」を検索し、次の単語をnew_wordに置き換えます。

for line in open_file: 
    spl = line.split(" ") 
    if "not" in spl: 
     idx_of_not = spl.index("not") 
     spl[idx_of_not + 1] = new_word 
    new_line = " ".join(spl) 
    print(new_line) 
関連する問題