【问题标题】:Reading and splitting a .csv file, which contains strings with commas in读取和拆分 .csv 文件,其中包含带逗号的字符串
【发布时间】:2020-12-09 16:15:37
【问题描述】:

我有一个 .csv 文件,看起来像这样:

1,2,"a,b",3
4,"c,d",5,6

我正在读取并存储在这样的数组中:

with open(filename, 'r') as f:
    data = f.readlines()
data = [line.split(',') for line in data]

这会导致这样的数组:

[['1','2','"a','b"','3']['4','"c','d"','5','6']]

但是,我想将数据数组的一个元素中的项目保留在双引号中,例如“a,b”(这是它们在 Excel 中的打开方式),如下所示:

[[1,2,'a,b',3][4,'c,d',5,6]]

有没有简单的方法在 Python 中实现这一点?

编辑:如果可能,最好不使用 csv 模块?

【问题讨论】:

  • 可以使用模块csv
  • 或者你也可以实现自己的解析器
  • @dcg 我试图避免使用它来保持清洁和简单,但如果这是唯一的方法......
  • 我觉得使用csv比自己动手要简单
  • 使用标准库中的csv 模块确实是这里的最佳选择。它使用起来很简单(请参阅下面使用它的答案),并且您可以确定所有可能出现的问题(例如,引用等)都已正确解决,并且在某些极端情况下您不会遇到错误。跨度>

标签: python string csv split


【解决方案1】:

您应该使用csv 模块:

import csv

with open('test.csv') as f:
    reader = csv.reader(f)
    
    for row in reader:
        print(row)

输出:

['1', '2', 'a,b', '3']
['4', 'c,d', '5', '6']

或者,如果您不想懒惰地阅读行并希望将所有行都放在一个列表中,就像您的问题一样,您可以简单地这样做:

with open('test.csv') as f:
    reader = csv.reader(f)
    data = list(reader)

print(data)        
# [['1', '2', 'a,b', '3'], ['4', 'c,d', '5', '6']]   

【讨论】:

    【解决方案2】:

    使用csv 模块:

    import csv
    
    with open('test.csv') as file:
        reader = csv.reader(file)
        
    data = [row for row in reader]
    

    【讨论】:

      【解决方案3】:

      如果你不想使用csv 模块,这个函数会返回你想要的输出

      def function(file_name):
          with open(file_name, 'r') as file:
              file_read = file.readlines()
              raw_data = [line.split(',') for line in file_read]
      
              file_data = list()
              place_0 = 0
              place_1 = 0
              ext_item = str()
              added = list()
              pre_final_list = list()
              pre_pure_list = list()
              pure_data = str()
              final_list = list()
      
              for List in raw_data:
                  for k, v in enumerate(List):
                      List[k] = v.rstrip()
              
              for line in raw_data:
                  if line == ['']:
                      continue
                  file_data.append(line)
      
              for line in file_data:
                  for key, value in enumerate(line):
                      if '"' in value[0] and '"' in value[-1]:
                          continue
                      if '"' in value[0]:
                          place_0 = key
                      if '"' in value[-1]:
                          place_1 = key
                      if place_1 != 0:
                          for ind in range(place_0, place_1+1):
                              added.append(line[ind])
                          for e_item in added:
                              if e_item == added[-1]:
                                  ext_item += e_item
                              else:
                                  ext_item += e_item + ','
                          line[place_0] = ext_item
                          for r_item_index in range(place_0+1, place_1+1):
                              line[r_item_index] = None
                          place_0 = 0
                          place_1 = 0
                          ext_item = str()
                          added = list()
      
              for line in file_data:
                  for value in line:
                      try:
                          value = int(value)
                      except: 
                          pass
                      if value == '\n':
                          continue
                      if not value is None:
                          pre_pure_list.append(value)
                  pre_final_list.append(pre_pure_list)
                  pre_pure_list = list()
              
      
              for List in pre_final_list:
                  for key, item in enumerate(List):
                      if type(item) is int or '"' not in item:
                          continue
                      for string in item:
                          if string == '"':
                              continue
                          pure_data += string
                      List[key] = pure_data
                      pure_data = str()
                  final_list.append(List)
      

      【讨论】:

        猜你喜欢
        • 2023-03-05
        • 2013-07-29
        • 1970-01-01
        • 1970-01-01
        • 2021-06-16
        • 2011-03-03
        • 2016-05-28
        • 1970-01-01
        相关资源
        最近更新 更多