簡體   English   中英

如何使用一個文本文件中的字符串搜索另一個文本,並使用另一個文本列創建一個新的文本文件?

[英]How to use strings from one text file to search another, and create a new text file with columns from another?

我需要使用一個文本文件中的字符串來搜索另一個,每次在第二個文本文件中匹配該字符串時,都在第二個字符串中搜索一個單詞word ,如果匹配,則使用從第二個文本文件,然后對第一個文本文件中的每個字符串重復此操作。

文字檔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

結果應該是三個單獨的文本文件(以文本文件中的字符串命名),每個包含第三列的字符串一個:

結果: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')

這是一個示例,其中輸入文件位於file1.txtfile2.txt中 我將文件1的內容及其關聯的輸出文件句柄緩存在字典 'files'中,然后在主循環結束時將其關閉。

在主循環中,我讀取file2.txt的每一行,將其剝離,並使用split方法將其標記為空格。 然后,我從第一個令牌中找到IP地址,並檢查其是否在“文件”中。 如果是這樣,我將第三列寫入相應的輸出文件。

最后一個循環關閉輸出文件句柄。

with open('file1.txt') as file1:
    files = {ip:open(ip + '.txt', 'w') for ip in [line.strip() for line in file1]}

with open('file2.txt') as file2:
    for line in file2:
        tokens = line.strip().split(' ')
        ip = tokens[0][3:]
        if ip in files:
            files[ip].write(tokens[2])
            files[ip].write('\r\n')

for f in files.values():
    f.close()

我相信以下代碼可以滿足您的要求:

file_1='file1.txt'
file_2='file2.txt'

my_string = 'word'

for line_1 in [l.rstrip() for l 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 line_1 == line_2_split[0][3:]:
                if my_string in line_2:
                    my_file.write(line_2_split[2] + '\n')

如果您打算在file_2的行中使用最后一個參數,請確保使用rstrip()將換行符剝離到第一個文件,我將其保留在file_2的行中。

# 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM