This article is to share with you that Python reads the data from the text and transforms it into an instance of Dataframe, which has a certain reference value, hoping to help people in need
In the technical question and answer to see a question like this, feel relatively common, just open an article write down.
Reads the data from the plain text format file "File_in" in the following format:
The output needs to be "file_out" in the following format:
The original format of the data is "Category: Content", with a blank line "\ n" as a sub-entry, converted into an entry line, in order to write the contents in sequence.
After reading, use pandas to set up the data called Dataframe form. This facilitates processing of data later. But the original format is not the usual table format, so do some simple processing first.
#coding: Utf8import sysfrom Pandas import DataFrame #DataFrame通常来装二维的表格import pandas as PD #pandas是流行的做数据分析的包 # The dictionary is created, and the keys and values are read from the file. The key is Nam,age ..., the value is lili,jim......dict_data={} #打开文件with open (' File_in.txt ', ' R ') as DF: #读每一行 for line in DF: # If this line is a newline, skip it, use the length of ' \ n ' to find the empty line if line.count (' \ n ') = = Len: continue #对每行清除前后空格 (if any), then use ":" To split For KV in [Line.strip (). Split (': ')]: #按照键, write the value in dict_data.setdefault (kv[0],[]). Append (Kv[1]) #print (dict_ Data) Look at the effect # This is to read the key to become a list columnsname=list (Dict_data.keys ()) #建立一个DataFrame, the column name is the key name, that is Nam,age......frame = DataFrame ( Dict_data,columns=columnsname) #把DataFrame输出到一个表, do not line name and column name Frame.to_csv (' File_out0.txt ', index=false,header=false )