从文件中删除空格并将其输出到另一个文件

时间:2019-09-03 03:29:20

标签: python

我想对文件进行排序,然后这部分工作了。排序后,我想从文件中删除每个空格行,并将其输出到另一个文件。

我只是想不通,我真的想要帮助。

bad_words = ["bad", "word"]


with open('naughtfile.txt') as oldfile, open('cleanfile', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

我想对文件进行排序,删除空白行并将其保存在另一个文件中。

3 个答案:

答案 0 :(得分:0)

首先,您将要读取文件的内容并将行拆分为一个列表。然后,您需要对该列表进行排序,然后将符合条件的列表项写入另一个文件。我不确定空白行是什么意思,但我认为这些只是空白行。

bad_words = ["bad", "word"]

with open('naughtfile.txt') as oldfile, open('cleanfile.txt', 'w') as newfile:
    content = oldfile.read().splitlines()
    content.sort()
    for line in content:
        if not any(bad_word in line for bad_word in bad_words) and not (line is "" or line.isspace()):
            newfile.write(line + '\n')

答案 1 :(得分:0)

from string import whitespace
from itertools import chain


bad_words = ['bad', 'words']

with open(filepath_1, 'r') as old_file, open(filepath_2, 'w') as new_file:
    lines = old_file.readlines()
    lines.sort()

    for line in lines:
        # chain together the whitespace list and bad_words list.
        if not any(strng in line for strng in chain(whitespace, bad_words)):
            # do stuff

答案 2 :(得分:0)

您还没有显示排序,所以我不确定您想在那里做什么。 至于其余的-我会使用正则表达式:

    import re
    # make regex that matches the bad words, plus empty lines
    bad_word = re.compile(r'bad|word|^\s*\n')
    # loop over the file and write the lines that don't match bad_word
    with open('naughtfile.txt') as oldfile, open('cleanfile.txt', 'w') as newfile:
        for line in oldfile:
            if bad_word.search(line):
                continue
            newfile.write(re.sub(r'\n', '', line))