如何在python中使用split()时避免特定单词之间的空格

时间:2015-10-05 16:50:07

标签: python

我正在使用split()将我的字符串转换为列表,但我发现一些我希望在一起的值是使用split()分隔的。以下是我的例子。

我的字符串为"Ambala Cantt. 1.2 Bitter Gourd 1200 2000 1500",在拆分后我希望它为[Ambala Cantt.,1.2,Bitter Gourd,1200,2000,1500],但我得到的结果为['Ambala', 'Cantt.', '1.2', 'Bitter', 'Gourd', '1200', '2000', '1500']。这是我不想要的。

为什么我使用split()因为我必须将我的字符串转换为列表,以便我可以将每个数据存储到我的数据库中。任何人都可以告诉我如何解决这个或更好的方法将我的字符串转换为列表。

2 个答案:

答案 0 :(得分:2)

您似乎正在尝试从http://agmarknet.nic.in/解析Mandi定价的结果。这些都有可预测的模式。

example = "Ambala Cantt. 1.2 Bitter Gourd 1200 2000 1500"
print([c.strip() for c in re.match(r"""
    (?P<market>[^0-9]+)
    (?P<arrivals>[^ ]+)
    (?P<variety>[^0-9]+)
    (?P<min>[0-9]+)
    \ (?P<max>[0-9]+)
    \ (?P<modal>[0-9]+)""",
    example,
    re.VERBOSE
).groups()])
['Ambala Cantt.', '1.2', 'Bitter Gourd', '1200', '2000', '1500']

答案 1 :(得分:1)

需要在输入中找到一致的模式(我假设此数据集中存在大量具有不一致分隔符的字符串) - 可能使用正则表达式执行拆分:https://docs.python.org/2/library/re.html

OpenRefine可以帮助数据清理字符串,如果它们来自输入文件。