【问题标题】:Using text file data, classification and make other text file in python在python中使用文本文件数据、分类和制作其他文本文件
【发布时间】:2017-02-18 08:21:50
【问题描述】:

使用 python,我想分离一些数据文件。 文件形式是文本文件,没有制表符,内部数据之间只有一个空格。

这里是示例文件,

//test.txt
  Class name age room fund.
  13 A 25 B101 300
  12 B 21 B102 200
  9 C 22 B103 200
  13 D 25 B102 100
  20 E 23 B105 100
  13 F 25 B103 300
  11 G 25 B104 100
  13 H 22 B101 300

我只想取包含特定数据的行,

班级:13,基金300

,然后保存另一个文本文件。

如果此代码有效,则制作文本文件就是这样

  //new_test.txt
  Class name age room fund.
  13 A 25 B101 300
  13 F 25 B103 300
  13 H 22 B101 300

谢谢。 港币

【问题讨论】:

    标签: python database python-3.x coding-style


    【解决方案1】:

    应该这样做。

    with open('new_test.txt','w') as new_file:
        with open('test.txt') as file:
            print(file.readline(),end='',file=new_file)
            for line in file:
                arr=line.strip().split()
                if arr[0]=='13' and arr[-1]=='300':
                    print(line,end='',file=new_file)
    

    但是,您应该在提问时包含您的代码。它确保本网站的目的得到服务。

    【讨论】:

    • 很抱歉,我忘了附上我的代码。谢谢你的指出。
    【解决方案2】:

    如果你想过滤你的数据:

    def filter_data(src_file, dest_file, filters):
        data = []
        with open(src_file) as read_file:
            header = [h.lower().strip('.') for h in read_file.readline().split()]
            for line in read_file:
                values = line.split()
                row = dict(zip(header, values))
                data.append(row)
                for k, v in filters.items():
                    if data and row.get(k, None) != v:
                        data.pop()
                        break
    
        with open(dest_file, 'w') as write_file:
            write_file.write(' '.join(header) + '\n')
            for row in data:
                write_file.write(' '.join(row.values()) + '\n')
    
    
    my_filters = {
        "class": "13",
        "fund": "300"
    }
    
    filter_data(src_file='test.txt', dest_file='new_test.txt', filters=my_filters)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      相关资源
      最近更新 更多