【问题标题】:Using Re.split to construct dictionary from file使用 Re.split 从文件构造字典
【发布时间】:2013-12-12 15:12:39
【问题描述】:

我正在读取一个文件,文件中的这一行给我带来了问题。它是

CSE 3380,professional,CSE 2315,note: MATH 3330 can be taken instead

我编写的用于拆分的代码是使用 re.split 模块来遵循这些类型的文件将遵循的模式,即

class(comma) catagory(comma) prereq class(comma) note(semicolon)

有多行都以相同的方式构建,但有些带有破折号和其他字符,因此基于非字母字符进行拆分的方法将无济于事。我想在逗号、逗号、逗号、分号处分开

course, catagory, pre, note = re.split(', |, |, |: ', line)

我收到一条错误消息,提示“ValueError:需要超过 1 个值才能解压”。我不知道为什么。我在其他不同的图案线中使用了这种方法,但是对于这个特定的图案我遇到了麻烦。

【问题讨论】:

  • 你可以打印 re.split(', |, |, |:', line) 看看返回什么,然后比较你需要什么。
  • 是的,我打印了它,但我在那里得到了那个错误
  • 这个在线测试器很有帮助 - regex101.com/#python

标签: python


【解决方案1】:

先用分号分割,再用逗号分割第一部分:

>>> var = 'CSE 3380,professional,CSE 2315,note: MATH 3330 can be taken instead'
>>> var = var.split(':')
>>> var
['CSE 3380,professional,CSE 2315,note', ' MATH 3330 can be taken instead']
>>> var[0] = var[0].split(',')
>>> var
[['CSE 3380', 'professional', 'CSE 2315', 'note'], ' MATH 3330 can be taken instead']

【讨论】:

    【解决方案2】:
    line = "CSE 3380,professional,CSE 2315,note: MATH 3330 can be taken instead"
    parts = re.match('^(.*?), ?(.*?), ?(.*?)(?:, ?note: ?(.*))$', line).groups()
    

    那么parts就是元组:

    ('CSE 3380', 'professional', 'CSE 2315', 'MATH 3330 can be taken instead')
    

    或将其作为更易于使用的字典:

    line = "CSE 3380,professional,CSE 2315,note: MATH 3330 can be taken instead"
    parts = re.match('^(?P<class>.*?), ?(?P<catagory>.*?), ?(?P<prereq>.*?)(?:, ?note: ?(?P<note>.*))$', line).groupdict()
    

    parts 设置为:

    {'note': 'MATH 3330 can be taken instead', 'prereq': 'CSE 2315', 'catagory': 'professional', 'class': 'CSE 3380'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      相关资源
      最近更新 更多