我有个问题,不知道如何创建矩阵
我有一本这样的字典:
dico = {
"banana": "sp_345",
"apple": "ap_456",
"pear": "pe_645",
}
像这样的文件:
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
s45678 f45678 f456789 ap_456_52546135
我要做的是创建一个矩阵,在这个矩阵中,我们可以从字典的行中找到n倍以上的值。你知道吗
我想这样继续:
步骤1创建一个包含相关值和行数的字典:
就像这样:
dictionary = {'1': 'sp_345_4567','pe_645_4567876', 'ap_456_45678', 'pe_645_4556789'; '2': 'sp_345_567', 'pe_645_45678'; '3:' 'pe_645_45678','ap_456_345678'; '4:' etc ..
然后,我想将这些值与我的第一个字典dico进行比较,比如看香蕉键出现在每一行中的次数(因此对我字典中的所有键都这样做),但问题是dico的值不等于dico的值,因为它们被跟随按此模式“\uw+”
我们的想法是制作一个最终的dict,它看起来像这样,以便能够在最后制作一个矩阵:
final_dict = {'line1': 'Banana' : '1' ; 'Apple': '1'; 'Pear':2; 'line2': etc ...
我的代码不起作用:
import pprint
import re
import csv
dico = {
"banana": "sp_345",
"apple": "ap_456",
"pear": "pe_645",
}
dictionary = {}
final_dict = {}
cnt = 0
with open("test.txt") as file :
reader = csv.reader(file, delimiter ='\t')
for li in reader:
grp = li
number = 1
for li in reader:
dictionary[number] = grp
number += 1
pprint.pprint(dictionary)
number_fruit = {}
for key1, val1 in dico.items():
for key2, val2 in dictionary.items():
if val1 == val2+'_\w+':
final_dict[key1] = val2
谢谢你的帮助
编辑:
我试过用听写理解法
import csv
import re
dico = {
"banana": "sp_345",
"apple": "ap_456",
"pear": "pe_645",
}
with open("test.txt") as file :
reader = csv.reader(file, delimiter ='\t')
for li in reader:
pattern = re.search(dico["banana"]+"_\w+", str(li))
if pattern:
final_dict = {"line" + str(index + 1):{key:line.count(text) for key, text in dico.items()} for index, line in enumerate(reader)}
print(final_dict)
但当我打印最后一本字典时,它只把香蕉放在0。。。你知道吗
{'line1': {'banana': 0, 'apple': 0, 'pear': 0}, 'line2': {'banana': 0, 'apple': 0, 'pear': 0}, 'line3': {'banana': 0, 'apple': 0, 'pear': 0}, 'line4': {'banana': 0, 'apple': 0, 'pear': 0}, 'line5': {'banana': 0, 'apple': 0, 'pear': 0}, 'line6': {'banana': 0, 'apple': 0, 'pear': 0}}
所以是的,现在看起来有点像我想要的,但发生率没有上升。。。。:/??你知道吗
为什么不起作用
你的测试
不起作用,因为您正在测试
val1
(可能是"sp_345_4567"
)和val2+'_\w+'
(可能是字符串,可能是"sp_345_\w+'"
)之间的字符串相等,并且它们不相等。你知道吗你能做些什么
您可以检查
"sp_345" in "sp_345_4567"
是否返回true
。你知道吗"sp_345"
在另一个字符串中出现的次数,您可以使用.count
来完成此操作:如何应用它来构建您的
final_dict
您可以使用字典理解以更简单的方式重写代码:
我正在用
"line1"
,"line2"
这样的键构建一个外部字典。。。对于它们中的每一个,值都是一个内部字典,里面有"banana"
或"apple"
这样的键,每个值都是它们出现在行中的次数。你知道吗如果您想知道
banana
在4
行上出现了多少次,您可以使用请注意,我建议使用列表而不是字典来将结果映射到行号,这样前面的查询将变成:
相关问题 更多 >
编程相关推荐