Home > Back-end >  Python matching data in two files
Python matching data in two files

Time:04-13

first of all, I am asking with the sample code in my hand under normal conditions, but I did not come up with the slightest solution for this issue.

I have two txts, the first txt:

French,01
Brasil,07
USA,23
England,34
Egypt,51
...

second txt

French
Paris
England
London
...

The first txt has more data than the second. My goal is to combine the data in the first txt according to what is in the second txt, for example: England,London,34

So far, I've tried something by converting txts to lists with the map(),reduce(), startswith(),zip() methods, but they do the matching either sequentially or randomly. how can i solve this?

list1 = ['French','01', 'Brasil','07']
list2 = ['French','Paris','England','London']

zip(list1,list2) ->> [('French','French'), ('01', Paris)]

CodePudding user response:

you can combine the two like this to create one common list and then do whatever you want with it

list1 = ['French','01', 'Brasil','07']
 list2 = ['French','Paris','England','London']
 for element in list1 :
    if element not in list2:
        list2.append(element)
    else:
        print(f"{element} is already in liste 2")
        print("liste2 : ")
        print(list2)

enter image description here

CodePudding user response:

In a comment that's now gone, you said the correspondence between the two lists is by line number, so I'm assuming that in this answer.

If what you're trying to do is just insert the line from text2 between the two elements on the line from text1, then the solution below will work.

I suspect your actual need may be slightly different, but this should give you what you need to solve your issue.

text1 = """French,01
Brasil,07
USA,23
England,34
Egypt,51
..."""

text2 = """French
Paris
England
London
..."""

list1 = [line.split(",") for line in text1.split("\n")]
list2 = text2.split("\n")

for line1, line2 in zip(list1, list2):
    newline = [line1[0], line2, line1[1]]
    print(",".join(newline))

It's basically just a matter of parsing and wrangling the data into the structure you need, there's not much magic to it.

  • Related