简体   繁体   English

如何将字符串拆分为多个部分以在循环中填充字典

[英]How to split a string into parts to populate a dict in a loop

I have a list of files I need to draw information from and I want to populate a dict with it.我有一个需要从中提取信息的文件列表,我想用它填充一个字典。 I know how to extract the information with a regular expression but the dict part mystifies me.我知道如何使用正则表达式提取信息,但 dict 部分让我感到困惑。

Code代码

import re

mylist = ['anna01','bobby03','dean120']
mydict = {}

Intended result预期结果

mydict = {'anna01': 1, 'bobby03':3, 'dean120':120} mydict = {'anna01':1,'bobby03':3,'dean120':120}

The regex I use in the actual problem is :我在实际问题中使用的正则表达式是:

for file in os.listdir(path):
    if file.endswith('.bmp'):
        image_name = file
        files.append(os.path.join(path, file))
        print(os.path.join(path, file))
        print(get_burst_from_name(file))
        print(image_name)
        pattern = '_\d*%'
        result = re.findall(pattern, file)[0]
        result = result.replace("_","")
        duty = result.replace("%","")
        print('duty=', duty)

where the key for a dict would be 'file' and the value would be 'duty' dict 的键是 'file',值是 'duty'

i think maybe this little code will help you:我想也许这个小代码会帮助你:

import re
mylist = ['anna01','bobby03','dean120']
myDict = {}
pattern = '(?P<Name>[^\d]+)(?P<Number>\d+)'
for index,value in enumerate(mylist):
    searchedRegex = re.search(pattern , value)
    if searchedRegex:
        number = searchedRegex.group("Number")
        myDict[value] = int(number)
print(myDict)

Output输出

{'anna01': 1, 'bobby03': 3, 'dean120': 120}

Exactly as you called.正如你所说的那样。

And if you just want to have their names(without number), then you can use group("Name") as i prepared it in the regex.如果你只想拥有他们的名字(没有数字),那么你可以使用我在正则表达式中准备的group("Name")

I think you'll get your desired output.我想你会得到你想要的输出。

import re
mylist = ['anna01','bobby03','dean120']
mydict = {}
for i in mylist:
    key = str(re.findall("\D+", i)[0])
    val = int(re.findall("\d+", i)[0])
    mydict[key] = val    
print("mydict = {}".format(mydict))

Output输出

mydict = {'anna': 1, 'bobby': 3, 'dean': 120}
mylist = ['anna01','bobby03','dean120']
mydict = {}

for i in mylist:
    word = ''
    num = ''
    for j in i:
        if j.isalpha():
            word += j
        else:
            num += j
    if num[0] == '0':
        num = num[1:]

    mydict[word] = int(num)

print(mydict)

Result结果

{'dean': 120, 'anna': 1, 'bobby': 3}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM