我需要从我读过的CSV文件中划分空白区域
import csv
aList=[]
with open(self.filename, 'r') as f:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
for row in reader:
aList.append(row)
# I need to strip the extra white space from each string in the row
return(aList)
答案 0 :(得分:34)
还有嵌入式格式参数:skipinitialspace(默认为false) http://docs.python.org/2/library/csv.html#csv-fmt-params
aList=[]
with open(self.filename, 'r') as f:
reader = csv.reader(f, skipinitialspace=False,delimiter=',', quoting=csv.QUOTE_NONE)
for row in reader:
aList.append(row)
return(aList)
答案 1 :(得分:9)
在我的情况下,我只关心在使用csv.DictReader
时从字段名称(也就是列标题,也就是字典键)中删除空格。
基于csv.DictReader
创建一个类,并覆盖fieldnames
属性以从每个字段名称中删除空格(也就是列标题,也就是字典键)。
通过获取常规的字段名列表,然后在创建新列表时迭代它,并从每个字段名称中删除空白,并将基础_fieldnames
属性设置为此新列表。
import csv
class DictReaderStrip(csv.DictReader):
@property
def fieldnames(self):
if self._fieldnames is None:
# Initialize self._fieldnames
# Note: DictReader is an old-style class, so can't use super()
csv.DictReader.fieldnames.fget(self)
if self._fieldnames is not None:
self._fieldnames = [name.strip() for name in self._fieldnames]
return self._fieldnames
答案 2 :(得分:6)
with open(self.filename, 'r') as f:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
return [[x.strip() for x in row] for row in reader]
答案 3 :(得分:3)
你可以这样做:
aList.append([element.strip() for element in row])
答案 4 :(得分:2)
您可以在文件周围创建一个包装器对象,在CSV阅读器看到之前剥离空格。这样,您甚至可以将csv文件与cvs.DictReader一起使用。
import re
class CSVSpaceStripper:
def __init__(self, filename):
self.fh = open(filename, "r")
self.surroundingWhiteSpace = re.compile("\s*;\s*")
self.leadingOrTrailingWhiteSpace = re.compile("^\s*|\s*$")
def close(self):
self.fh.close()
self.fh = None
def __iter__(self):
return self
def next(self):
line = self.fh.next()
line = self.surroundingWhiteSpace.sub(";", line)
line = self.leadingOrTrailingWhiteSpace.sub("", line)
return line
然后像这样使用它:
o = csv.reader(CSVSpaceStripper(filename), delimiter=";")
o = csv.DictReader(CSVSpaceStripper(filename), delimiter=";")
我将";"
硬编码为分隔符。将代码推广到任何分隔符都留给读者练习。
答案 5 :(得分:1)
使用Pandas读取CSV(或Excel文件)并使用此自定义功能修剪它。
#Definition for strippping whitespace
def trim(dataset):
trim = lambda x: x.strip() if type(x) is str else x
return dataset.applymap(trim)
您现在可以将修剪(CSV / Excel)应用到您的代码中(如循环的一部分等)
dataset = trim(pd.read_csv(dataset))
dataset = trim(pd.read_excel(dataset))
答案 6 :(得分:1)
解析后格式化单元格最节省内存的方法是通过generators。像这样:
with open(self.filename, 'r') as f:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
for row in reader:
yield (cell.strip() for cell in row)
但可能值得将其移至一个函数,您可以使用该函数来不断进行调整并避免即将到来的迭代。例如:
nulls = {'NULL', 'null', 'None', ''}
def clean(reader):
def clean(row):
for cell in row:
cell = cell.strip()
yield None if cell in nulls else cell
for row in reader:
yield clean(row)
或者它可以用于分解一个类:
def factory(reader):
fields = next(reader)
def clean(row):
for cell in row:
cell = cell.strip()
yield None if cell in nulls else cell
for row in reader:
yield dict(zip(fields, clean(row)))
答案 7 :(得分:0)
这是适用于 Python3 的 Daniel Kullmann 出色的解决方案:
import re
class CSVSpaceStripper:
"""strip whitespaces around delimiters in the file
NB has hardcoded delimiter ";"
"""
def __init__(self, filename):
self.fh = open(filename, "r")
self.surroundingWhiteSpace = re.compile(r"\s*;\s*")
self.leadingOrTrailingWhiteSpace = re.compile(r"^\s*|\s*$")
def close(self):
self.fh.close()
self.fh = None
def __iter__(self):
return self
def __next__(self):
line = self.fh.readline()
line = self.surroundingWhiteSpace.sub(";", line)
line = self.leadingOrTrailingWhiteSpace.sub("", line)
return line
答案 8 :(得分:0)
我想出了一个非常简单的解决方案:
import csv
with open('filename.csv') as f:
reader = csv.DictReader(f)
rows = [ { k.strip(): v.strip() for k,v in row.items() } for row in reader ]