【问题标题】:Python split string to multiple substrings with single quotations and a trailing commaPython将字符串拆分为带有单引号和尾随逗号的多个子字符串
【发布时间】:2017-08-15 16:17:51
【问题描述】:

我正在尝试将 csv 多行上的字符串拆分为三个子字符串,我需要将它们保留在同一行,同时在该行的子字符串 2 和 3 上添加单引号,后跟逗号。

csv 中的行格式如下:

12345678/ABCDE.pdf
12345678/ABCDE.pdf
12345678/ABCDE.pdf

由于我是 Python 新手,我尝试在返回前两个不带 / 的子字符串的行上进行拆分,但我不确定如何获得最终所需的输出。

'12345678', 'ABCDE.pdf'

我希望输出如下所示

12345678,'/ABCDE.pdf','ABCDE',
12345678,'/ABCDE.pdf','ABCDE',
12345678,'/ABCDE.pdf','ABCDE',

最后一个字符串包含 pdf 的标题,不带文件扩展名。

任何帮助将不胜感激。

【问题讨论】:

  • 所以再拆分一次...

标签: python string csv substring


【解决方案1】:

再次使用split,无需正则表达式即可轻松构造所需的输出字符串。

In [22]: %%timeit
    ...: s = '''12345678/ABCDE.pdf
    ...: 12345678/ABCDE.pdf
    ...: 12345678/ABCDE.pdf'''
    ...: for l in s.splitlines():
    ...:     s_parts = l.split('/')
    ...:     new_s = '{},\'/{}\',\'{}\','.format(s_parts[0], s_parts[1], s_parts[1].split('.')[0])
    ...:
100000 loops, best of 3: 3.55 µs per loop

输出:

Out[24]: "12345678,'/ABCDE.pdf','ABCDE',"

为了比较,发布的也可以正常工作的正则表达式解决方案具有以下运行时性能。此处的性能差异并不太显着,但由于要处理大量项目,这可能是一个因素。

In [25]: %%timeit
    ...: s = ["12345678/ABCDE.pdf",
    ...:       "12345678/ABCDE.pdf",
    ...:       "12345678/ABCDE.pdf"]
    ...: new_s = [[re.findall("\d+", i)[0], "/"+i.split("/")[-1], re.findall("[A
    ...: -Z]+", i)[0]] for i in s]
    ...:
100000 loops, best of 3: 11.6 µs per loop

【讨论】:

    【解决方案2】:

    您可以使用re.split()re.findall()

    s = ["12345678/ABCDE.pdf",
          "12345678/ABCDE.pdf",
          "12345678/ABCDE.pdf"]
    new_s = [[re.findall("\d+", i)[0], "/"+i.split("/")[-1], re.findall("[A-Z]+", i)[0]] for i in s]
    

    输出:

    [['12345678', '/ABCDE.pdf', 'ABCDE'], ['12345678', '/ABCDE.pdf', 'ABCDE'], ['12345678', '/ABCDE.pdf', 'ABCDE']]
    

    【讨论】:

      猜你喜欢
      • 2011-04-16
      • 2018-09-26
      • 1970-01-01
      • 2012-11-16
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      相关资源
      最近更新 更多