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

Python 如何将拆分字符串转换为字典?,python,algorithm,Python,Algorithm,我正在制作一个程序,它以如下方式接受字符串:“鲍勃演奏,画简,尼基住在房子里”。活动和进行此活动的人员可以随机放置。此人的姓名以大写字母开头。带有名称的活动始终用逗号分隔。字典中的活动应始终放在名称之后。输出应该是以下方式的字典:{'Bob':'plays','Jane':'draws','Nicky':'LivesinaHouse'} 我不知道该怎么做,首先,把绳子分成几个人,其次,把这些人分成活动和人。我一直使用简单的字典,其中只有一个拆分,因此,在这里创建字典对我来说相当复杂 有谁能帮我解

我正在制作一个程序,它以如下方式接受字符串:“鲍勃演奏,画简,尼基住在房子里”。活动和进行此活动的人员可以随机放置。此人的姓名以大写字母开头。带有名称的活动始终用逗号分隔。字典中的活动应始终放在名称之后。输出应该是以下方式的字典:{'Bob':'plays','Jane':'draws','Nicky':'LivesinaHouse'}

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


有谁能帮我解决这个问题,也许能给我一些建议?我将非常感谢。

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

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)
输出


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

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)
输出


您可以使用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(',')}
输出:

或者对于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])}

您可以使用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(',')}
输出:

或者对于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])}

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

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)

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

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)
def f(s):
 ls = s.split(',')
 d = {}
 for e in ls:
    key = [w for w in e.split(' ') if w.istitle()][0]
    val = ' '.join([w for w in e.split(' ') if not w.istitle()])
    d[key] = val
return d

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

活动是否总是用逗号分隔?Bob居住的房子中yoda样式字符串的键和值应该是什么?您应该首先确定输入字符串的格式,要使用什么分隔符来确定与名称关联的值,等等。例如,您可以确定字典键值的每个条目都用逗号与其他条目分开,然后按照以大写开头的键对其进行解析,rest是值逻辑,从那里创建dict。活动是否总是用逗号分隔?Bob居住的房子中yoda样式字符串的键和值应该是什么?您应该首先确定输入字符串的格式,使用什么分隔符来确定与名称关联的值,等等例如,您可以确定字典键值的每个条目都用逗号与其他条目分开,然后按照以大写开头的键对其进行解析,其余为值逻辑,并从中创建dict。
def f(s):
 ls = s.split(',')
 d = {}
 for e in ls:
    key = [w for w in e.split(' ') if w.istitle()][0]
    val = ' '.join([w for w in e.split(' ') if not w.istitle()])
    d[key] = val
return d