使用 Python 仅将所需内容从文本文件复制到 Excel

Copy only the required content from the text file to Excel using Python

我在文本文件中有大量数据,包括日期、大学名称、毕业年份等详细信息,它还包含学生的姓名和唯一 ID,如下所示。此外,文本文件未格式化且包含大量数据。

Group list of all the students 
5 June 2020/KCT/2015 Group BRD Rahul e34 Pradeep e44 Venkat r45 Azhar t54  
6 June 2020/BCT/2012 Group ZRD Akash e14 Pavan e24 Vipul r15 Asad t14
7 June 2020/KBN/2014 Group KRD Fairoz e45 Kumar e55 Akshay e44 Vivek e99 etc

当我 运行 一个 python 代码时,我需要 excel/csv sheet 中的输出,它只显示名称(列 1)和唯一 ID(列 2)一行一行。基本上在 excel sheet 中,我只想在 Excel sheet 中显示名称和唯一 ID,如下所示,我只需要显示名称和唯一 ID。我不需要 excel sheet.

中的其他数据
Rahul    e34 
Pradeep  e44 
Venkat   r45 
Azhar    t54
Akash    e14 
Pavan    e24 
Vipul    r15 
Asad     t14
Fairoz   e45 
Kumar    e55 
Akshay   e44 
Vivek    e99

这是我试过的

import pandas as pd
df = pd.read_csv("C:\Users\PMishra\Desktop\Document.txt", sep='\t' )
df.to_csv('C:\Users\PMishra\Desktop\Demo.csv')

当我 运行 这样做时,它只会将文本文件中的所有内容复制到 excel sheet。我想在 excel/csv sheet 中输出,它逐行显示所有名称(Column1)和唯一 ID(Column2)。我是 python (Spyder) 的新手。如何分别获取column1和column2中的name和ids?

您的第一行必须是列的名称,然后您可以只显示名称为:

的两列
dfnew = df[["namecolum1","namecolum1"]]

dfnew.to_csv('C:\Users\PMishra\Desktop\Demo.csv')

您可以通过使用 usecols 参数调用 read_csv() 来仅加载选定的列,see the Documentation.

# this would load only column 0, 1, and 2
# you can use column names too: ['col0', 'col1', 'col2']
dummy_example = pandas.read_csv('path_to/your_file.csv', usecols=[0, 1, 2])

但是,对于你的情况,我会在没有 pandas;

的情况下进行
input_file = 'path_to/input_file.txt'
output_file = 'path_to/output_file.csv'

# open both files, output in "append" mode
with open(input_file, 'r') as file, open(output_file, 'a+') as out_file:
    for line in file.readlines():

       try:
            # split at 'Group'
            line = line.split('Group')[1]

            # split and select after Group name
            line = line.split()[1:]

        except:
            # no 'Group' or no data thereafter
            # skip to the next loop 
            continue

        # create name-id pairs
        name_id = list(zip(line[2::2], line[1::2]))

        for tup in name_id:
            # make comma separated string 
            string = ','.join(tup) + '\n'

            # append to the outfile 
            out_file.write(string)

输出文件;

Pradeep,e34
Venkat,e44
Azhar,r45
Pavan,e14
Vipul,e24
Asad,r15
Kumar,e45
Akshay,e55
Vivek,e44
Pradeep,e34
Venkat,e44
Azhar,r45
Pavan,e14
Vipul,e24
Asad,r15
Kumar,e45
Akshay,e55
Vivek,e44