28

テキストファイルからテキストを読み取り、行を読み取り、特定の文字列を含む行を削除しようとしています(この場合は「悪い」と「いたずら」)。私が書いたコードは次のようになります。

infile = file('./oldfile.txt')

newopen = open('./newfile.txt', 'w')
for line in infile :

    if 'bad' in line:
        line = line.replace('.' , '')
    if 'naughty' in line:
        line = line.replace('.', '')
    else:
        newopen.write(line)

newopen.close()

このように書いたのですが、うまくいきません。

重要なことの 1 つは、テキストの内容が次のような場合です。

good baby
bad boy
good boy
normal boy

出力に空の行を含めたくありません。好きではない:

good baby

good boy
normal boy

しかし、このように:

good baby
good boy
normal boy

上記のコードから何を編集すればよいですか?

4

10 に答える 10

78

このように、コードをよりシンプルで読みやすくすることができます

bad_words = ['bad', 'naughty']

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

Context Manager任意の.

于 2012-08-15T12:43:47.373 に答える
7

置換を行う代わりに、その行を新しいファイルに含めることはできません。

for line in infile :
     if 'bad' not in line and 'naughty' not in line:
            newopen.write(line)
于 2012-08-15T12:11:50.137 に答える
2

は最後のelseにのみ接続されifます。あなたがしたいelif

if 'bad' in line:
    pass
elif 'naughty' in line:
    pass
else:
    newopen.write(line)

また、これらの行を書かないので、行の置換を削除したことにも注意してください。

于 2012-08-15T12:15:50.610 に答える
0
to_skip = ("bad", "naughty")
out_handle = open("testout", "w")

with open("testin", "r") as handle:
    for line in handle:
        if set(line.split(" ")).intersection(to_skip):
            continue
        out_handle.write(line)
out_handle.close()
于 2012-08-15T12:27:14.247 に答える