Python:解析文件名,拆分和删除多个字符

时间:2017-11-01 19:41:52

标签: python csv string-parsing

我有一个包含图片的文件夹(.jpg),我需要将文件名提取为CSV,使用'_'将它们分成多个列(带标题),并删除多个字符。

我已使用以下内容部分完成此操作:

import os, csv

with open('filepath.csv', 'w') as f:
    writer = csv.writer(f)
    for path, dirs, files in os.walk('dirpath'):
        for item in files:
        writer.writerow([item])

with open('filepath.csv', 'w') as inf:
    with open ('outfile.csv', 'w') as outf:
        for line in inf:
            outf.write(','.join(line.split('_')))

示例文件名: firstname_lastname_uniqueid_date_latUKN_longUKN_club.jpg 上面代码的结果会返回firstnamelastnameuniqueiddatelatUKNlongUKNclub.jpg

这是我正在寻找的架构,但我也希望从'lat''long'解析latUKNlongUKN ,以及删除字符串末尾的.jpg。我需要删除字符串'lat''long',因为文件名包含纬度/经度,但'lat''long'会在解析中出现(例如{lat12.34, long54.67'latUKN' 1}})

如何删除/删除这些其他字符,并添加标题?如果没有纬度或经度,我如何将此部分留空而不是填充字符串'longUKN'John_Doe_2259153_20171102_latUKN_longUKN_club1.jpg John_Doe_2259153_20171031_lat123.00_long456.00_club1.jpg Jane_Doe_5964264_20171101_latUKN_longUKN_club2.jpg Jane_Doe_5964264_20171029_lat789.00_long012.00_club2.jpg Joe_Smith_1234564_20171001_lat345.00_long678.00_club3.jpg 。是否可以在整个目录上运行并输出单个csv?

示例数据

John|Doe|2259153|20171102|latUKN|longUKN|club1.jpg
John|Doe|2259153|20171031|lat123.00|long456.00|club1.jpg
Jane|Doe|5964264|20171101|latUKN|longUKN|club2.jpg
Jane|Doe|5964264|20171029|lat789.00|long012.00|club2.jpg
Joe|Smith|1234564|20171001|lat345.00|long678.00|club3.jpg

数据在当前代码中的显示方式:

John|Doe|2259153|20171102|UKN|UKN|club1
John|Doe|2259153|20171031|123.00|456.00|club1
Jane|Doe|5964264|20171101|UKN|UKN|club2
Jane|Doe|5964264|20171029|789.00|l012.00|club2
Joe|Smith|1234564|20171001|345.00|678.00|club3

我希望数据看起来如何:

{{1}}

3 个答案:

答案 0 :(得分:0)

如果a是给定的字符串,你可以使用这样的东西吗?

    a="ukn_abcd.jpg"
    for i in "ukn",".jpg":
         a=a.replace(i,"")

您可以创建这样的函数并将字符串传递给它以删除这些不需要的字符

答案 1 :(得分:0)

  import csv
  l=[]
  with open("sf.csv") as csvfile:
  reader = csv.reader(csvfile)
  for row in reader:
       l.append(row)
  #print(l)
  new_l=str(l).replace("lat","").replace(".jpg","").replace("long","")
  #print(new_l)
  with open("output_sf", "w") as csvfile:
      for data in str(new_l).split(","):
          #print(str(data))
          csvfile.write(str(data))

所以,当我按照你上面的例子中给出的输入文件时,这就是我得到的输出。现在你可以尝试将它写入你的txt / csv文件。

  

[['约翰| Doe的| 2259153 | 20171102 | UKN | UKN | club1'   '约翰|李四| 2259153 | 20171031 | 123.00 | 456.00 | club1'   '珍|李四| 5964264 | 20171101 | UKN | UKN | club2'   '珍|李四| 5964264 | 20171029 | 789.00 | 012.00 | club2'   '乔|史密斯| 1234564 | 20171001 | 345.00 | 678.00 | club3']]

答案 2 :(得分:0)

由于两个答案都围绕着使用find / replace,并没有完全解决问题,我使用以下内容来完成任务:

import csv

infile = open('path', 'r')
outfile = open('path', 'r')

findlist = ['lat', 'long', '.jpg.']
replacelist = ["", "", ""]

rep = dict(zip(findlist, replacelist))

s = infile.read()
for item, replacement in zip(findlist, replacelist):
    s = s.replace(item, replacement)
outfile.write(s)