【问题标题】:How to use the split command to tackle a string from the back end如何使用 split 命令从后端处理字符串
【发布时间】:2016-06-13 05:25:11
【问题描述】:

我正在尝试解析逗号分隔字符串的不同部分。

这里有两个示例字符串:

低北极,阿拉斯加,植物群落,v.35, 2005, p. 761.

Visualizing Frost Boils,科学与工程中的挑战,v.13,2005 年,p。 18.

我需要将页码、年份、卷 (v.13)、期刊和标题存储到单独的变量中。我想从后面处理这些字符串,因为标题中可能有逗号(计划用逗号分隔),并且字符串的后端非常一致。任何有关如何向后解决此问题的指示都会非常有帮助。谢谢!

第二个例子:

page = 'p.18'
year = '2005'
volume = 'v.13'
journal = 'Challenges in Science and Engineering' 
title = 'Visualizing Frost Boils'

【问题讨论】:

  • 有许多关于 SO 的问题涉及反转字符串。这就是为什么我相信你会收到反对票。
  • 不要太多关于反转字符串,因为它是从右边分裂的 - str.rsplit(',', 4) 是你要找的

标签: python string parsing split


【解决方案1】:

你可以使用rsplit():

>>> s = 'Visualizing Frost Boils,Challenges in Science and Engineering, v.13, 2005, p. 18.'
>>> title, journal, volume, year, page = [entry.strip() for entry in  s.rsplit(',', 4)]
>>> page
'p. 18.'
>>> year
'2005'
>>> volume
'v.13'
>>> journal
'Challenges in Science and Engineering'
>>> title
'Visualizing Frost Boils'

您将字符串从右边的 rsplit(',' 4) 以逗号分隔,并将拆分次数限制为 4。 entry.strip() 删除条目周围的空白。

【讨论】:

    【解决方案2】:
    title,journal,vol,year,page = my_string.rsplit(',',4)
    

    我认为是你想要的

    【讨论】:

    • 我知道你的意思。 :)
    【解决方案3】:

    如果逗号的数量始终相同,您可以编写一个函数来获取各种逗号的索引,然后返回索引之间的字符串。

    例如,如果我们计算有 4 个逗号,我们会有:

    title = string[:comma_index1]
    year = string[comma_index1:comma_index2]
    volume = string[comma_index2:comma_index3]
    year = string[comma_index3:comma_index4]
    page = string[comma_index4:]
    

    不过,这可能是一种天真的方式。

    【讨论】:

    • 下面 Mike Müller 建议的 rsplit 方法是一个更好的解决方案。
    【解决方案4】:

    我个人会使用正则表达式。

    >>> import re
    >>> c = re.compile('(.*), v.(\d*), (\d*), p. (\d*).')
    >>> c.match('Plant communities and soils in cryoturbated tundra along a bioclimate gradient in the Low Arctic, Alaska,Phytocoenologia, v.35, 2005, p. 761.').group(1,2,3,4)
    
    ('Plant communities and soils in cryoturbated tundra along a bioclimate gradient in the Low Arctic, Alaska,Phytocoenologia', '35', '2005', '761')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      相关资源
      最近更新 更多