如何从txt文件中获取列名并放入pandas数据框中?

huangapple go评论57阅读模式
英文:

How to get column names from txt file into pandas data frame?

问题

我有一个下面的txt文件,其中有不同的列名,我想从表中提取所有列名,但不包括数据类型等信息,然后将其存储到pandas数据框中。
英文:

I have a txt file below with different column names, I want to extract all the column names without the data types etc. from the table into the pandas dataframe.

create table ad.TrackData
(
    track_id         int unsigned auto_increment primary key,
    ads_id           int                  null,
    ads_name         varchar(45)          null,
    play_time        timestamp            null,
    package_id       int                  null,
    package_name     varchar(45)          null,
    company_id       int                  null,
    company_name     varchar(45)          null,
    click_time       timestamp            null,
    demographic      varchar(300)         null,
    status           tinyint(1) default 0 null
);

I have no idea how I am supposed to do this, it would be very much appreciated if anyone could teach me some ways to perform this.

答案1

得分: 0

with open('file.txt', 'r') as f:
  txt = f.read()
  lines = txt.split('\n')
  columnNames = []
  for line in lines:
    if line.startswith('    '):
      columnNames.append(line.split('    ')[1])
  print(columnNames)
英文:

First, you must save that text to file.txt. Then run a python script below:

with open('file.txt', 'r') as f:
  txt = f.read()
  lines = txt.split('\n')
  columnNames = []
  for line in lines:
    if line.startswith('    '):
      columnNames.append(line.split('    ')[1])
  print(columnNames)

the output must be :

['track_id', 'ads_id', 'ads_name', 'play_time', 'package_id', 'package_name', 'company_id', 'company_name', 'click_time', 'demographic', 'status']

huangapple
  • 本文由 发表于 2023年2月6日 16:28:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358913.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定