在多个文件中查找下一个单词并替换

时间:2016-12-07 18:41:34

标签: file python-3.x

我目录中有很多文件(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

任何想法!!!!!!

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

您收到此错误是因为read_file是字符串列表,而不是单个字符串。 list 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)) 方法会引发您看到的错误,因为您的文件中的任何行都不是"不是"。顺便说一下,index字符串方法也会引发错误,而index返回-1。

您需要循环测试线:

open

完成文件后关闭文件非常重要,因此我已将with调用添加到'not'块,即使出现错误,也会为您关闭文件

实际更换/删除的工作原理是首先将行拆分为单词,然后将不遵循prev_word的单词附加到另一个缓冲区中。完成该行后,它将连接回一个带空格的字符串,并附加到输出行列表中。

请注意,我只在None循环之前将for初始化为'not',而不是每行。这允许以for结尾的行将替换值转移到下一行的第一个单词。

如果要将处理后的文件写回原始文件,请将以下代码段添加到文件列表中最外层with open(file, 'w') as open_file: open_file.write('\n'.join(output_lines)) 循环的末尾:

SELECT * FROM person
LEFT JOIN vehicle ON person.id = vehicle.owner
WHERE person.id IN (SELECT ID FROM PERSON LIMIT 3);