【问题标题】:Read file with data python使用数据python读取文件
【发布时间】:2018-07-26 01:43:58
【问题描述】:

我有一个包含如下数据的文件:

{day=20180711,stime_ms=187989.786,p=0.90},
{day=20180711,stime_ms=188004.036,p=0.95},

---成千上万个这样的字符串

我用 python 读取了这个文件:

path="D:\_py\data.lua"
f = open(path)
for line in f.readlines():
    print (line)
f.close()

我想在 matplotlib 中构建图表:

x 轴 - stime_ms

y 轴 - p

如果我有这样的数据,这对我来说很容易:

stime_ms=[187989.786, 188004.036] 
p=[0.90, 0.95]

那么,如何从文件中获取数据? 谢谢

【问题讨论】:

  • 与其编写自己的 Lua 解析器,不如直接使用 luaparser 模块来加载文件并检索条目?
  • 今天是lua文件。明天将是txt文件。扩展无关紧要

标签: python python-3.x file


【解决方案1】:

您可以使用正则表达式模块re 来解析您的输入。 类似的东西:

import re

data_re = re.compile(r"stime_ms=(?P<stime_ms>\d+\.\d+').*p=(?P<p>\d+\.\d+)")
stime_ms = []
p = []
with open('data.txt') as f:

    for m in map(data_re.search, f):

        if m:
            stime_ms.append(float(m.group('stime_ms')))
            p.append(float(m.group('p')))
        else:
            # report data parsing error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多