在处理要加载到sql数据库中的csv时遇到问题。
csv有几个自由文本字段,并且数据中有一些换行符。这导致一行被分成两行。
我想做的是设置代码,以在行的分割字符少于预期的时候基本用空格替换新的行字符。因为我知道要期待多少列。我真的不知道该怎么做。我当前的代码如下。
batch = list()
with open(file, "r", errors='ignore') as f:
for l in f.readlines()[1:]:
# append the processed row to the batch list
# processed row meaning we strip down the fields to remove redundant data
# and add Nones if the length of the row is not up to the FIELDS_COUNT
list_pre = l.split("#|#")
batch.append([i.strip() for i in list_pre])
所以输入看起来像这样:
col1#|#col2#|#col3#|#col4#|#col5
col1#|#col2#|#co
l3#|#col4#|#col5
col1#|#col2#|#col3#|#col4#|#col5
col1#|#col2#|#col3#|#col4#|#col5
预期输出:
['col1','col2','col3','col4','col5']
['col1','col2','col3','col4','col5']
['col1','col2','col3','col4','col5']
['col1','col2','col3','col4','col5']
答案 0 :(得分:0)
您可以尝试以下操作:
Set<Question> questions = new TreeSet<>();
for(int i=0; i<15; i++)
{
questions.add(new Question());
}
for (Question question : questions) {
System.out.println(question.getQuestion());
}
答案 1 :(得分:0)
好的,这就是我的解决方法,基本上我说过,如果字段少于总列数,则追加下一行。老实说,如果一行中有多行新行,这是行不通的,因此它可能在将来某个时候行不通,但目前行之有效
file = 'fakecsv.txt'
batch = list()
list_pre0 = []
print(len(list_pre0))
with open(file, "r", errors='ignore') as f:
for l in f.readlines()[1:]:
list_pre = l.split("#|#")
if len(list_pre) < 4:
print(len(list_pre))
if len(list_pre0) == 0:
list_pre0 = list_pre
else:
replace_value = list_pre0[-1].replace('\n','') + list_pre[0]
print('replace value equals: ' + replace_value)
del list_pre0[-1]
del list_pre[0]
list_pre0.append(replace_value)
combined = list_pre0 + list_pre
batch.append([i.strip() for i in combined])
list_pre0 = []
continue
print(len(list_pre))
batch.append([i.strip() for i in list_pre])
print(batch)