程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python does not use a third-party library to read tabular string data from TXT text documents and perform data processing operations

編輯:Python

Catalog

  • Data specifications
  • The core idea
  • Pre operation
  • Data manipulation
  • Non tabular .txt File string

Data specifications

.txt Tabular data are as follows , Where the delimiter is ’\t’, Finally, through the newline character ’\n’ Line break

The core idea

Open file , Exclude the first row that is not related to the data , The valid data starting from the second row is passed to the tail 、 Split into two-dimensional list form which is easy to operate , adopt int() or float() Convert numeric string data into numeric data

Pre operation

with open(filepath) as f:#filepath Customize 
f.readline()# Remove the first row that is not related to the data 
lines=f.readlines()# Read the remaining rows with data 
for i in range(len(lines)):# Cycle pair 8 Line to operate 
if lines[i].endswith('\n'):
lines[i]=lines[i][:-1] # Put the at the end of the string \n Get rid of 
lines[i]=lines[i].split('\t') # With \t Division 

At this time, the processed lines The data is :

[['Lucy', '88', '79'], ['Lilei', '90', '88'], ['Lily', '78', '82'], ['Sam', '80', '76'], ['Dean', '79', '68'], ['Jean', '75', '78'], ['Bill', '78', '82'], ['Jim', '86', '88'], ['brook', '76', '86']]

It becomes a set of two-dimensional lists , Since then, the data operation has been connected with txt The file is completely irrelevant

Data manipulation

The first element of each list element is Name, The second is Score1, The third one is Score2, So if you put Score1 and Score2 Each attached with 50% The weight of , stay for The two-dimensional list is processed as follows in the loop

Score=int(lines[i][1])*0.5+int(lines[i][2])*0.5#i Is a cyclic variable 

The second and third data of each list element can be weighted , The first one. Name The data is output together

print(lines[i][0]+' The total score of '+str(Score))# Output the total score 

The result is :

Lucy The total score of 83.5
Lilei The total score of 89.0
Lily The total score of 80.0
Sam The total score of 78.0
Dean The total score of 73.5
Jean The total score of 76.5
Bill The total score of 80.0
Jim The total score of 87.0
brook The total score of 81.0

Simple data processing for tabular string is realized

Non tabular .txt File string

Not a tabular one is actually simpler , And it is impossible to involve data operation , After reading, there is no .txt What happened to the file . As a string , You can operate with string functions


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved