あるテキスト ファイルの文字列を使用して別のテキスト ファイルを検索し、2 番目のテキスト ファイルで文字列が一致するたびに、2 番目の文字列で単語を検索し、word
一致する場合は、2 番目のテキスト ファイルから特定の列を含む 3 番目のテキスト ファイルを作成する必要があります。最初のテキスト ファイルのすべての文字列に対して繰り返します。
例
テキストファイル 1:
10.2.1.1
10.2.1.2
10.2.1.3
テキストファイル 2:
IP=10.2.1.4 word=apple thing=car name=joe
IP=10.2.1.3 word=apple thing=car name=joe
IP=10.2.1.1 word=apple thing=car name=joe
IP=10.2.1.2 word=apple thing=car name=joe
IP=10.2.1.1 word=apple thing=car name=joe
IP=10.2.1.3 word=apple thing=car name=joe
結果は、3 番目の列を含む文字列ごとに 1 つずつ、3 つの別個のテキスト ファイル (テキスト ファイル 1 の文字列にちなんで名付けられた) になります。
結果: 10.2.1.3.txt
thing=car
thing=car
等
これまでのところ、私のコードは次のようになります。
with open(file_1) as list_file:
for string in (line.strip() for line in list_file):
if string in file_2:
if "word" in file_2:
column2 = line.split()[2]
x = open(line+".txt", "a")
with x as new_file:
new_file.write(column2)
私の質問は次のとおりです。このコードはそれを行うための最良の方法ですか? 重要な「ショートカット」が欠けているように感じます。
Olafur Osvaldssonによる最終的なコード:
for line_1 in open(file_1):
with open(line_1+'.txt', 'a') as my_file:
for line_2 in open(file_2):
line_2_split = line_2.split(' ')
if "word" in line_2:
if "word 2" in line_2:
my_file.write(line_2_split[2] + '\n')