0

あるテキスト ファイルの文字列を使用して別のテキスト ファイルを検索し、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')
4

3 に答える 3

1
# define files
file1 = "file1.txt"
file2 = "file2.txt"

ip_patterns = set() # I assume that all patterns fits the memory

# filling ip_patterns
with open(file1) as fp:
    for line in fp: 
        ip_patterns.add(line.strip()) # adding pattern to the set


word_to_match = "apple" # pattern for the "word" field
wanted_fields = ['name', 'thing'] # fields to write

with open(file2) as fp:
    for line in fp:
        values = dict(map(lambda x: x.split('='), line.split()))
        if values['IP'] in ip_patterns and values['word'] == word_to_match:
            out = open(values['IP'] + '.txt', 'a')
            for k in wanted_fields:
                out.write("%s=%s\n" % (k, values[k])) # writing to file
            out.close()
于 2013-08-21T13:45:01.847 に答える