Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用正则表达式从字符串创建字典以获取组?_Python_Regex_Dictionary - Fatal编程技术网

Python 如何使用正则表达式从字符串创建字典以获取组?

Python 如何使用正则表达式从字符串创建字典以获取组?,python,regex,dictionary,Python,Regex,Dictionary,我有一项复杂的任务要完成: 从一个字符串中,我希望能够对特定类别中的单词进行分类 s = 'Age 63 years, female 35%; race or ethnic group: White 68%, Black 5%, Asian 19%, other 8%' d = function(s) print(d) {"age": "63 years", "gender: "female 35%"

我有一项复杂的任务要完成: 从一个字符串中,我希望能够对特定类别中的单词进行分类

s = 'Age 63 years, female 35%; race or ethnic group: White 68%, Black 5%, Asian 19%, other 8%'
d = function(s)
print(d)
      {"age": "63 years",
       "gender: "female 35%",
       "race": "White 68%, Black 5%, Asian 19%, other 8%"}
我必须指出,并非所有字符串的格式都相同,但在所有字符串中都有一组有限的类别(
年龄
性别
种族
地区
),但有些字符串在4个类别中只有1个或2个

s = 'Age 63 years, female 35%; race or ethnic group: White 68%, Black 5%, Asian 19%, other 8%'
d = function(s)
print(d)
      {"age": "63 years",
       "gender: "female 35%",
       "race": "White 68%, Black 5%, Asian 19%, other 8%"}
以下是一些其他玩具线:

s2 = 'Age 71 years, male 64%'
s3 = 'Age 64 years, female 21%,
Race or ethnicity: White 66%, Black 5%, Asian 18%, other 11%
Region: N. America 7%, Latin America 17%, W. Europe or other 24%, central Europe 33%, Asia-Pacific 18%
如您所见,有一些模式:

  • age
    前面没有任何
    :'
  • 性别
    记录为女性或男性
  • race
    region
    后面跟着
    :'
我感兴趣的是收集与类别对应的所有信息,如我的玩具示例中种族类别所示

我需要的是:

  • 使用适当的捕获组编写正则表达式模式以获得结果
  • 将匹配项转换为字典:我看到了使用
    .groupdict()
    方法的解决方案
  • 我在编写将返回上述组的正则表达式模式时遇到问题

    我看到了一个类似问题的有趣解决方案:。
    但是我很难将它应用到我的正则表达式中。

    你可以通过一组正则表达式传递输入字符串,每个正则表达式试图提取你在问题中提到的一列,而不是找到一个黄金正则表达式来处理所有情况。差不多

    ageMatch = re.match( r'Age\s+(\d+)\s+years?', s, re.I)
    if ageMatch:
        //Use ageMatch.group(1) to form part of your dict
    
    genderMatch = re.match( r'(male|female)\s+(\d+)\s*%', s, re.I)
    if genderMatch:
        //Use genderMatch.group(1) genderMatch.group (2) to form part of your dict
        
    

    看起来您正在寻找基于一个示例字符串的通用解决方案。所有字符串都是这种形式吗?请澄清在何种情况下进行SEP操作?(对于年龄,必须显示qord年龄,可能的性别只有男性或女性?顺序总是与示例中的顺序相同?),第二,您尝试过什么吗?分享它。嗨,你们两个@MarkMeyer和@YossiLevi!我更新了我的问题以纳入您的问题。提前谢谢!您可以使用第一个模式,
    Age.\d{1,}.\w{1,}
    ,发现它,从字符串中删除,然后处理不带年龄的子字符串以获得第一个模式,然后使用
    ^\w+\s{1,}\d{1,}%
    ,remove等等来发现
    女性35%
    。要找到第一个模式,您可以使用
    ^\w+\s{0,}\d{1,}\s{0,}\w+
    ,从字符串中删除它,并对子字符串执行相同的
    ^\w+\s{1,}\d{1,}%
    操作,等等。谢谢您的提示!这实际上是一个很好的选择!!