2016-12-07 105 views
0

我在目錄(file1.txt,file2.txt,...)中有很多文件,並且我想查找('not')後面的單詞並將其替換。查找多個文件中的下一個單詞並替換

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是字符串列表,而不是一個字符串你得到這個錯誤。 listindex方法會引發您所看到的錯誤,因爲文件中沒有行是完全「不」。順便說一句,字符串的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)) 

當你與他們所做的要關閉文件是很重要的,所以我已經添加了open呼叫到with塊,這將關閉即使存在錯誤,也是爲您提供的文件。

實際的替換/刪除的工作原理是首先將行拆分爲單詞,然後將不遵循'not'的單詞附加到另一個緩衝區中。當這一行完成後,它會被連接回一個帶有空格的字符串並附加到輸出行列表中。

請注意,我初始化prev_wordNone只有一次,在外部for循環之前,而不是每一行。這允許以'not'結尾的行將替換移交到下一行的第一個單詞。

如果你想寫入處理的文件恢復到原始文件,下面的片段添加到最for遍歷文件列表的末尾:

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

搜索單詞「不」,並用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) 
相關問題