如何拆分为列

NXW*_*NXW 5 python split

我有一个包含两个数据集的文件,我想将其作为两列读入 Python。

数据格式如下:

xxx yyy    xxx yyy   xxx yyy
Run Code Online (Sandbox Code Playgroud)

等等,所以我明白我需要以某种方式把它分开。我是 Python 的新手(并且对编程相对较新),所以到目前为止我一直在努力。目前我尝试使用:

def read(file):

    column1=[]
    column2=[]
    readfile = open(file, 'r')
    a = (readfile.read())
    readfile.close()
Run Code Online (Sandbox Code Playgroud)

我将如何将读取的文件拆分为 column1 和 column2?

Alv*_*oAV 0

这是一个关于获取第 1 列中的 xxx 值和第 2 列中的 yyy 值的简单示例。

重要的!您的文件数据必须类似于:

xxx yyy xxx yyy xxx yyy
组之间有 4 个空格(xxx yyy xxx yyy),每对数据之间有 1 个空格(xxx yyy)


例如,您可以使用另一个分隔符逻辑,如下所示:

xxx,yyy/xxx,yyy/xxx,yyy   
你只需更改data_separator=','column_separator='/'

或者

xxx-yyy/xxx-yyy/xxx-yyy   
你只需更改data_separator='-'column_separator='/'

def read(file):
    column1=[]
    column2= []
    readfile = open(file, 'r')
    data_separator = ' '  # one space to separate xxx and yyy
    column_separator = '    '  # 4 spaces to separate groups xxx,yyy    xxx,yyy

    for line in readfile.readlines():  # In case you have more than 1 line
         line = line.rstrip('\n')  # Remove EOF from line
         print line

         columns = line.split(column_separator)  # Get the data groups 
         # columns now is an array like ['xxx yyy', 'xxx yyy', 'xxx yyy']

         for column in columns:
             if not column: continue  # If column is empty, ignore it
             column1.append(column.split(data_separator)[0])
             column2.append(column.split(data_separator)[1])
    readfile.close()
Run Code Online (Sandbox Code Playgroud)

我有一个文本文件,其中包含xxx yyy aaa bbb ttt hhh调用该函数后的结果:

column1 = ['xxx', 'aaa', 'ttt']
column2 = ['yyy', 'bbb', 'hhh']
Run Code Online (Sandbox Code Playgroud)