Search code examples
pythonfilepython-itertools

Why doesn't the number of occurences increase?


Here is my problem: I have a dictionary (dico) and I want to count the number of times, for 2 different keys, that they both appear on the same line in the file "file.tsv" which looks like this:

sp_345_4567 pe_645_4567876  ap_456_45678    pe_645_4556789 ...
sp_345_567  pe_645_45678 ...
pe_645_45678    ap_456_345678 ...
sp_345_56789    ap_456_345 ...
pe_645_45678    ap_456_345678 ...
sp_345_56789    ap_456_345 ...
...

For example, the values of the banana and apple keys appear on line 1 so no matter how many times they appear they are still present, and so we have 1 line in common, and I want to do it on all the lines of the file

For that I added the pattern '_\w+' behind each value and then made a regex with the function re.search.

from itertools import product
import csv

dico = {
    "banana": "sp_345",
    "apple": "ap_456",
    "pear": "pe_345",
    "cherry": "ap_345",
    "coco": "sp_543",
}

counter = {}
with open("file.tsv") as file:
    reader = csv.reader(file, delimiter="\t")
    for line in reader:
        for key1, key2 in product(dico, dico):
            if key1 >= key2:
                continue
            counter[key1, key2] = 0
            k1 = k2 = False
            for el in line:
                if re.search(dico[key1]+'_\w+', el):
                    k1 = True
                elif re.search(dico[key2]+'_\w+', el):
                    k2 = True
                if k1 and k2:
                    counter[key1, key2] += 1
                    break

for key, val in counter.items():
    print(key, val)

But the occurrences is stop at 0:

Apple banana 0
pear banana 0
pear apple 0

Solution

  • k1 and k2 can't both be True because you are initializing both with False and setting at most one to True.

    elif re.search(dico[key2]+'_\w+', el):
        k2 = True
    

    should be

    if re.search(dico[key2]+'_\w+', el):
         k2 = True