2017-05-14 27 views
1

説明するのが難しい種類ですが、スクリプトには文字の束を持つテキストファイルがあります。私はまた、すべてのマスターレコードを持っています。私は最初のファイルを取って、マスターレコードと一致しているすべてを削除したい。最終的には、最初のファイルには表示されないエントリもあります。Python、別のテキストファイルにあるテキストからテキストを削除するにはどうしたらいいですか?

まずファイル:

Cow 
Duck 
Sheep 

マスターレコード:すべてのヘルプは高く評価され

Duck 
Sheep 
Cat 
Dog 

ここでは例のようなものです!

+6

結果はCowですか?また、これを実装しようとしましたか?あなたのコードを表示し、あなたの実装に何があるのか​​を示すことができますか? – idjaw

+0

また、各単語の位置は重要ですか?それとも、もしそれが1つの言葉が両方にあるのを見たらそれを取り除かないのですか? –

+0

また、大きなファイルですか?重複を保つかどうか? –

答えて

0

読むマスターファイルけれどもとセットにラインを入れ、その後、マスターセット内の単語に2つ目のファイルの行を比較する:

コード:

# read in the master file and put each line into a set 
with open('master') as f: 
    master = {w.strip() for w in f.readlines()} 

# read through the second file and keep each line not in master 
with open('file1') as f: 
    allowed = [w.strip() for w in f.readlines() if w.strip() not in master] 

# show the allowed lines 
for w in allowed: 
    print(w) 
0

これを試してみてください(両方のリストがファイルであることを前提としています)。

master = open('master.txt', 'r').read() 
f = open('file.txt', 'r').read() 
f_arr = f.split('\n') 
master_arr = master.split('\n') 
fin_arr = [] 
for i in range(len(f_arr)): 
    if not f_arr[i] in master_arr: 
     fin_arr.append(f_arr[i]) 
final = '\n'.join(fin_arr) 
0

注:これにはファイルの読み書きは含まれません。

データ:誰も見たくないワンライナーリストの内包のための今すぐ

file = """ 
cow 
duck 
sheep 
""" 

master_record = """ 
duck 
sheep 
cat 
dog 
""" 

print([i for i in [x for x in file.replace('\n', ' ').split(' ') if x in master_record.replace('\n', ' ').split(' ')] if i]) 

ファイル内のすべての単語のリストを返します。マスターレコードにも表示されます。それを分割

found = [] 

# Loop through ever word in `file`, replacing newlines with spaces, 
for word in file.replace('\n', ' ').split(' '): 
    # Check if the word is in the master file, 
    if word in master_record.replace('\n', ' ').split(' '): 
     # Make sure the word contains something, 
     if word: 
      # Add this word to found, 
      found += [word] 

# Print what we found, 
print(found) 

・ホープ、このことができます!

-Coolq

関連する問題