这是我的问题,
我有一个字典(dico),我想计算两个不同键的次数,它们都出现在文件“ test”的同一行中,看起来像这样;
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 ....
...
例如,香蕉和苹果键的值出现在第1行,所以无论它们出现多少次,它们仍然存在,所以我们共有1行,我想在文件
为此,我添加了模式'_。在每个值后面,然后使用函数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)
但是出现的位置被阻止为0
Apple banana 0
pear banana 0
pear apple 0
有人可以帮忙吗?
k1
和k2
都不能同时是True
,因为您要同时使用False
进行初始化,并且最多将True
设置为1。
elif re.search(dico[key2]+'_\w+', el):
k2 = True
应该是
if re.search(dico[key2]+'_\w+', el):
k2 = True
您的电话
counter[key1, key2] = 0
仅应在(key1,key2)还没有值时发生。
也
elif re.search(dico[key2]+'_\w+', el):
应该是
if re.search(dico[key2]+'_\w+', el):
否则,找到键1时将永远找不到键2