我有一个输入文件,它的头部是这样的:
AdditionalCookout.create!([
{day_id: 275, cookout_id: 71, description: "Sample text, that, is ,driving , me, crazy"},
{day_id: 275, cookout_id: 87, description: nil},
{day_id: 276, cookout_id: 71, description: nil},
{day_id: 276, cookout_id: 87, description: nil},
{day_id: 277, cookout_id: 92, description: nil},
{day_id: 277, cookout_id: 71, description: nil},
我正在尝试将每一行解析为它自己的对象。但是,我不能用逗号分隔,因为有些描述中有逗号..
尝试了我能找到的 StackOverflow 帖子中的这两行正则表达式:
re.split(r', (?=(?:"[^"]*?(?: [^"]*)*))|, (?=[^",]+(?:,|$))', content[x])
和:
[y.strip() for y in content[x].split(''',(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''')]
然而..他们都输出
['{day_id: 275', 'cookout_id: 71, description: "Feeling ambitious? If you really want to exhaust yourself today, consider adding some additional stationary cardio."},']
Turns into:
day_id: 275
cookout_id: 71, description: "Feeling ambitious? If you really want to exhaust yourself today, consider adding some additional stationary cardio.",
有什么办法可以解决这个问题,以便将每一行正确地分成三个独立的部分,而不是两个?谢谢
请您参考如下方法:
尝试使用 PyYAML 来解析它。在我的例子中工作。 https://pypi.python.org/pypi/PyYAML .然后你就可以避免正则表达式的头痛。
import yaml
yaml.load('{day_id: 275, cookout_id: 71, description: "Sample text, that, is,driving , me, crazy"}')
{'cookout_id': 71,
'day_id': 275,
'description': 'Sample text, that, is,driving , me, crazy'}
