如何将拆分字符串转换为字典?

2024-06-25 22:55:18 发布

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

我正在制作一个程序,它以以下方式接受字符串:'Bob plays, draws Jane, Nicky lives in a house'。活动和进行此活动的人员可以随机放置。此人的姓名以大写字母开头。带有名称的活动始终用逗号分隔。字典中的活动应始终放在名称之后。输出应该是以下方式的字典:{'Bob': 'plays', 'Jane': 'draws', 'Nicky': 'lives in a house'}

我不知道该怎么做,首先,把绳子分成几个人,其次,把这些人分成活动和人。我一直使用简单的字典,其中只有一个拆分,因此,在这里创建字典对我来说相当复杂

有谁能帮我解决这个问题,也许能给我一些建议?我会非常感激的


Tags: 字符串in程序名称字典人员方式house
3条回答

正如你所说,名字是以大写字母开头的。所以我写了这段代码,希望对大家有所帮助:

string = 'Bob plays, draws Jane, Nicky lives in a house'
splitedString = string.split(",")
finalDict = {}
for sentence in splitedString:
    splitedSentence = sentence.split()
    name = ''
    toDo = ''
    for word in splitedSentence:
        if(word[0].isupper()):
            name = word
        else:
            toDo = toDo + " " + word
    finalDict[name.strip()] = toDo.strip()
print(finalDict)

输出

{'Bob': 'plays', 'Jane': 'draws', 'Nicky': 'lives in a house'}

因此,为了做到这一点,除非您想进行自然语言处理,否则您需要指定对什么构成名称和什么构成动作的限制。例如,如果您说名称是以大写字母开头的拉丁字母字符的集合,而非名称的任何操作(例如,它不能以大写字母开头)可以执行以下操作:

import re

p = re.compile(r'^(.*)([A-Z][a-z]+)(.*)$')
a = 'Bob plays, draws Jane, Nicky lives in a house'

# split expressions by comma
b = a.split(',')
# create an empty dictionary to hold the result
d = {}

# process all comma-separated expressions
for i in b:
    # strip removes blank lines before and after the string
    i = i.strip()
    res = re.match(p, i)
    if res.group(1) != '' and res.group(3) != '':
        raise ValueError("Entry ({}) cannot be processed".format(i))
    person = res.group(2)
    action = res.group(1) if res.group(1) != '' else res.group(3)
    # set the dictionary entry with key - first element
    # and value - second
    d[person.strip()] = action.strip()
    
print(d)

在这里,我只是使用正则表达式来指定名称

您可以使用regex将单词与大写字母匹配,并使用dict comprehension创建dict:

import re    
s = 'Bob plays, draws Jane, Nicky lives in a house'    
{re.search(r'\b[A-Z].*?\b', text.strip())[0]:text.replace(re.search(r'\b[A-Z].*?\b', text.strip())[0], '').strip() for text in s.split(',')}

输出:

{'Bob': 'plays', 'Jane': 'draws', 'Nicky': 'lives in a house'}

或者对于Python 3.8或更新版本:

{match:text.replace(match, '').strip() for text in s.split(',') if (match := re.search(r'\b[A-Z].*?\b', text.strip())[0])}

相关问题 更多 >