Python 为什么我会丢失文件中的字段?

Python 为什么我会丢失文件中的字段?,python,Python,我想将输入数据转换为CSV,以使用WEKA进行数据挖掘过程。我不知道为什么我在程序的输出中丢失了一些字段。 我认为问题出在程序的后半部分,当我在新文件中写入输出时,我缺少了一些分隔符,使得WEKA无法处理该文件 我留下了代码和输入文件 PYTHON: #!usr/bin/env python # -*- coding: utf-8 -*- f = open('datos_terr.csv', 'rb') fout = open('salida.csv', 'w') lines = f.read

我想将输入数据转换为CSV,以使用WEKA进行数据挖掘过程。我不知道为什么我在程序的输出中丢失了一些字段。 我认为问题出在程序的后半部分,当我在新文件中写入输出时,我缺少了一些分隔符,使得WEKA无法处理该文件

我留下了代码和输入文件

PYTHON:

#!usr/bin/env python
# -*- coding: utf-8 -*-

f = open('datos_terr.csv', 'rb')
fout = open('salida.csv', 'w')
lines = f.readlines()
first = lines[0].strip("\r\n")
fout.write(lines[0] + "\n")
for line in lines[1:]:
    """
    Removing tab characters, used to separate the values. Then I insert NULL values between them for uknown fields. I add "" characters to strings 
    to make WEKA able to accept them, and I put the separation value. I remove the ending tabs and they are subtituted by commas. I write the line
    to the output file and close both.

    Elimino los caracteres de tabulación, que son los que representan la separación. Luego los separo por ellos tras añadir el NULL para
    los campos de los que no conozco los datos. Añado comillas a las cadenas de texto para que WEKA las acepte y añado el caracter de separación.
    Elimino las tabulaciones que me sobren al final y luego los sustituyo por comas. Las escribo al fichero de salida y cierro ambos.
    """
    line = line.strip("\r\n")
    line = line.replace("'", "")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t\t", "\tNULL\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t\t", "\tNULL\tNULL\tNULL\t")
    line = line.replace("\t\t\t", "\tNULL\tNULL\t")
    line = line.replace("\t\t", "\tNULL\t")
    new_line = ""
    data = line.split("\t")
    for word in data:
        word = word.strip(" ")
        word = word.replace(" ", "")
        if word.isspace():
            word = "NULL"
        if "," in word:
            new_line += '"' + word + '"'
        else:
            if not word.isdigit() and not word == "NULL" and not isinstance(word, float) and not word == "":
                new_line += '"' + word + '"\t'
            else:
                new_line += word + "\t"
    new_line = new_line.strip('\t')
    new_line = new_line.replace("\t", ",")
    fout.write(new_line + "\n")
f.close()
fout.close()
可以在此URL中查看输入文件:


我将使用
csv
模块获取字段列表,并处理这些字段。更干净的代码通常更容易发现错误。您可以在不使用csv模块的情况下执行相同的操作,但该模块已经可以使用几种不同的格式—例如,它将自动引用带有分隔符的字段,因此您不需要在word:中进行
if”,“in”检查。您还可以通过一个简单的选项检查文档,查看是否为您处理了任何其他检查:

您的代码为每一行创建一个新字符串,因此我刚刚为每一行创建了一个新列表,作为编写代码的等效方法:

with open('datos_terr.csv', 'rb') as incsv, open('salida.csv', 'wb') as outcsv:
    # Read from the first, saying that tab is the field delimiter
    myreader = csv.reader(incsv, delimiter='\t')
    # , is the default, here for explanation
    mywriter = csv.writer(outcsv, delimiter=',')
    for row in myreader:
        # row is a list of the fields.
        newrow = list()
        for field in row:
            # No spaces allowed in fields
            field = field.strip()
            field = field.replace(' ', '')
            # single quotes to be removed, as per original code
            field = field.replace("'", '')
            if len(field) < 1:
                field = 'NULL'
            newrow.append(field)
        mywriter.writerow(newrow)
        # print ', '.join(newrow)
打开('datos_terr.csv','rb')作为incsv,打开('salida.csv','wb')作为outcsv:
#从第一个开始读,说tab是字段分隔符
myreader=csv.reader(incsv,分隔符='\t')
#,是默认值,请在此进行解释
mywriter=csv.writer(outcsv,分隔符=',')
对于myreader中的行:
#行是字段的列表。
newrow=list()
对于第行中的字段:
#字段中不允许有空格
field=field.strip()
字段=字段。替换(“”,“”)
#根据原始代码删除单引号
字段=字段。替换(“”,“”)
如果len(字段)<1:
字段='NULL'
newrow.append(字段)
mywriter.writerow(纽罗)
#打印“,”。联接(新行)

建议,使用
RegExp
替换字符或只替换
行。替换(“\t”,““\tNULL”)
并删除最后一个
NULL
解决方案中的问题是,如果下一个值不是\t,我会丢失它,因为我没有选项卡。