0

私は2つのテキストファイルからデータを取得しています.file1のデータがfile2にもある場合は、file1からデータを削除する必要があります.

import sys
File1 = open("file1.txt")
File2 = open("file2.txt")
for lines in File1:
    for line in File2:
        for lines in line:
            print lines
File1
you
you to
you too
why
toh

File2
you
you to

私のプログラムは file2 にある単語を表示しますが、 file2 に存在する file1 からエントリを削除するにはどうすればよいですか?

4

4 に答える 4

2

fileinputモジュールを使用してinplace=True、2 番目のファイルsetをルックアップ目的でロードすることができます...

import fileinput

with open('file2.txt') as fin:
    exclude = set(line.rstrip() for line in fin)

for line in fileinput.input('file1.txt', inplace=True):
    if line.rstrip() not in exclude:
        print line,
于 2013-03-01T05:43:11.110 に答える
1

file2がメモリに収まる場合。各行のルックアップset()を回避するために使用できます。O(n)

with open('file2.txt') as file2:
    entries = set(file2.read().splitlines())

with open('file1.txt') as file1, open('output.txt', 'w') as outfile:
    outfile.writelines(line for line in file1
                       if line.rstrip("\n") not in entries)
于 2013-03-01T05:33:24.233 に答える
1

あなたはそのようなことをすることができます:

file2 = open('file2.txt').readlines()
with open('result.txt', 'w') as result:
    for line in open('file1.txt'):
        if line not in file2:
            result.write(line)

「file1.txt」は変更されませんが、代わりに、file2 にはない file1 の行を含む別のファイル「result.txt」が作成されます。

于 2013-02-28T15:10:44.547 に答える
1
import string

file1 = set(map(string.rstrip, open("f1").readlines()))
file2 = set(map(string.rstrip, open("f2").readlines()))

print ( file1 - file2 ) | file2

与える

set(['other great lines of text', 'from a file', 'against.', 'keep text', 'which is wanted to compare', 'This is', 'some text', 'keep is wanted to compare'])

f1

This is 
keep text
from a file 
keep is wanted to compare
against.

f2

This is 
some text
from a file 
which is wanted to compare
against.
other great lines of text

問題がある場合とない場合がある順序を維持することに問題があります。

于 2013-02-28T16:31:55.230 に答える