如何在Python字典中查找和存储字符串中出现的子字符串的数量?

2024-05-01 02:59:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题,不知道如何创建矩阵

我有一本这样的字典:

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}}

所以是的,现在看起来有点像我想要的,但发生率没有上升。。。。:/??你知道吗


Tags: inimportapplefordictionary字典spdict
1条回答
网友
1楼 · 发布于 2024-05-01 02:59:52

为什么不起作用

你的测试

if val1 == val2+'_\w+':
    ...

不起作用,因为您正在测试val1(可能是"sp_345_4567")和val2+'_\w+'(可能是字符串,可能是"sp_345_\w+'")之间的字符串相等,并且它们不相等。你知道吗

你能做些什么

  • 例如,您可能需要测试容器
if val1 in val2:
    ...

您可以检查"sp_345" in "sp_345_4567"是否返回true。你知道吗

  • 您可能还想实际计算"sp_345"在另一个字符串中出现的次数,您可以使用.count来完成此操作:
"sp_345_567  pe_645_45678".count("sp_345") # returns 1
"sp_345_567  pe_645_45678".count("_") # returns 2
  • 您也可以使用正则表达式来实现:
import re
pattern = "sp_345_" + "\\w+"

if re.match(pattern, "sp_345_4567"):
    # pattern was found! Do stuff here.
    pass

# alternatively:
print(re.findall(pattern, "sp_345_4567"))
# prints ['sp_345_4567']

如何应用它来构建您的final_dict

您可以使用字典理解以更简单的方式重写代码:

import csv

dico = {
    "banana": "sp_345",
    "apple": "ap_456",
    "pear": "pe_645",
}

with open("test.txt") as file :
    reader = csv.reader(file, delimiter ='\t')
    final_dict = {"line" + str(index + 1):{key:line.count(text) for key, text in dico.items()} for index, line in enumerate(reader)}

我正在用"line1""line2"这样的键构建一个外部字典。。。对于它们中的每一个,值都是一个内部字典,里面有"banana""apple"这样的键,每个值都是它们出现在行中的次数。你知道吗

如果您想知道banana4行上出现了多少次,您可以使用

print(final_dict["line4"]["banana"])

请注意,我建议使用列表而不是字典来将结果映射到行号,这样前面的查询将变成:

print(final_list[3]["banana"])

相关问题 更多 >