Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Take this invoice.txt for example

Invoice Number

INV-3337

Order Number

12345

Invoice Date

January 25, 2016

Due Date

January 31, 2016

And this is what dict.txt looks like:

Invoice Date

Invoice Number

Due Date

Order Number

I am trying to find keywords from 'dict.txt' in 'invoice.txt' and then add it and the text which comes after it (but before the next keyword) in a 2 column datatable.

So it would look like :

col1 ----- col2

Invoice number ------ INV-3337

order number ---- 12345

Here is what I have done till now

with open('C:invoice.txt') as f:
    invoices = list(f)

with open('C:dict.txt') as f:
    for line in f:
        dict = line.strip()
        for invoice in invoices:
            if dict in invoice:
                print invoice

This is working but the ordering is all wrong (it is as in dict.txt and not as in invoice.txt)

i.e. The output is

Invoice Date

Invoice Number

Due Date

Order Number

instead of the order in the invoice.txt , which is

invoice number

order number

invoice date

due date

Can you help me with how I should proceed further ?

Thank You.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

This should work. You can load your invoice data into a list, and your dict data into a set for easy lookup.

with open('C:invoice.txt') as f:
    invoice_data = [line.strip() for line in f if line.strip()] 

with open('C:dict.txt') as f:
    dict_data = set([line.strip() for line in f if line.strip()])

Now iterate over invoices, 2 at a time and print out the line sets that match.

for i in range(0, len(invoice_data), 2):
    if invoice_data[i] in dict_data:
        print(invoive_data[i: i + 2])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...