如何使用python读取.txt数据?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (890)

我有这样一个.txt文件:

# 经纬度
x1 = 11.21  
x2 = 11.51

y1 = 27.84  
y2 = 10.08

time: 201510010000  
变量名: val1  
[1.1,1.2,1.3]  
变量名: va2    
[1.0,1.01,1.02]  

time: 201510010100  
变量名: val1  
[2.1,2.2,2.3]  
变量名: va2  
[2.01,2.02,2.03]

time: 2015020000  
变量名: val1  
[3.0,3.1,3.2]  
变量名: val2  
[3.01,3.02,3.03]

time: 2015020100  
变量名: val1  
[4.0,4.1,4.2]  
变量名: val2    
[401,4.02,4.03]

我希望用这样的python来阅读它:

with open('text.txt','r',encoding='utf-8') as f:
    lines = f.readlines()
    for line in lines:
        print(line,)
提问于
用户回答回答于

要以所需的格式获取数据,可以将相关部分添加到字典中,然后将其转换为Dataaframe:

import ast
import pandas as pd

with open('text.txt','r', encoding='utf-8') as f:
    lines = f.readlines()
    d = {"time":[],
         "val1":[],
         "val2":[]}

    for i, line in enumerate(lines):
        if line[:5] == "time:":
            time = line.strip().split()[-1]

            #Reading string representations of lists as lists
            v1 = ast.literal_eval(lines[i+2].strip())
            v2 = ast.literal_eval(lines[i+4].strip())

            #Counting number of vals per date
            n1 = len(v1)
            n2 = len(v2)

            #Padding values if any are missing
            if n1 > n2:
                v2 += [None] * n1-n2
            elif n2 > n1:
                v1 += [None] * n2-n1

            d["time"].extend([time] * max(n1,n2))
            d["val1"].extend(v1)
            d["val2"].extend(v2)

df = pd.DataFrame(d)

print(df)

            time  val1    val2
0   201510010000   1.1    1.00
1   201510010000   1.2    1.01
2   201510010000   1.3    1.02
3   201510010100   2.1    2.01
4   201510010100   2.2    2.02
5   201510010100   2.3    2.03
6     2015020000   3.0    3.01
7     2015020000   3.1    3.02
8     2015020000   3.2    3.03
9     2015020100   4.0  401.00
10    2015020100   4.1    4.02
11    2015020100   4.2    4.03
用户回答回答于

我建议您更改.txt格式并在.ini文件或.csv中进行转换。不管怎样,你可以用字典。

dict = {}
file = open("file.txt")
text = file.readline()
i=0
for i in range (text.lenght):
   if text[i][0:5]=="time":
      dict[text[i]] = []
      dict[text[i]].append(text[i+2])
      dict[text[i]].append(text[i+4])

该代码可能适用于您的文件,但如果您更改格式将更容易在dict中存储数据。 我希望我能提供帮助。

扫码关注云+社区

领取腾讯云代金券