【问题标题】:Extract data from string in python从python中的字符串中提取数据
【发布时间】:2016-11-13 09:59:54
【问题描述】:

我有一个 .csv 文件,其中的数据按行构造为 [datetime, "(data1, data2)"],我已设法将数据作为 time 和 temp 导入 python,我面临的问题是如何分隔 @987654325将 @ 字符串转换为浮点格式的两个 new_temp 列,以便稍后用于绘图?

到目前为止我的代码是:

import csv
import matplotlib.dates as dates

def getColumn(filename, column):
    results = csv.reader(open('logfile.csv'), delimiter = ",")
    return [result[column] for result in results]
time = getColumn("logfile.csv",0)
temp = getColumn("logfile.csv",1)
new_time = dates.datestr2num(time)
new_temp = [???]

当我print temp 我得到['(0.0, 0.0)', '(64.4164, 66.2503)', '(63.4768, 65.4108)', '(62.7148, 64.6278)', '(62.0408, 63.9625)', '(61.456, 63.2638)', '(61.0234, 62.837)', '(60.6823, 62.317)',...etc]

如果有人可以帮助我,请提前感谢。

【问题讨论】:

  • 附带说明,您应该只阅读 CSV 一次,然后提取列。目前,您一遍又一遍地阅读整个文件。
  • 我检查了该解决方案并编写了 make_tuple(temp) 并得到错误:ValueError:格式错误的字符串。而且我还尝试了 tuple(int(x) for x in temp[1:-1].split(',')) 并得到错误: AttributeError: 'list' object has no attribute 'split'
  • 我的解决方案有问题吗?它应该可以工作。
  • 感谢这位似乎创造了魔法的人。

标签: python string python-2.7 floating-point


【解决方案1】:

从答案开始 Parse a tuple from a string?

from ast import literal_eval as make_tuple
temp = ['(0.0, 0.0)', '(64.4164, 66.2503)', '(63.4768, 65.4108)', '(62.7148, 64.6278)', '(62.0408, 63.9625)', '(61.456, 63.2638)', '(61.0234, 62.837)', '(60.6823, 62.317)']

tuples = [make_tuple(stringtuple) for stringtuple in temp]

你有一个双精度元组数组。

我取消删除了该帖子并将其作为完整答案,因为显然它还不够清楚,无法引用其他帖子。

【讨论】:

【解决方案2】:

您可以使用此代码:

import re
string = "['(0.0, 0.0)', '(64.4164, 66.2503)', '(63.4768, 65.4108)', '(62.7148, 64.6278)', '(62.0408, 63.9625)', '(61.456, 63.2638)', '(61.0234, 62.837)', '(60.6823, 62.317)']"
data = re.findall('[+-]?\d+\.\d+e?[+-]?\d*', string)
data = zip(data[0::2], data[1::2])
print [float(d[0]) for d in data]
print [float(d[1]) for d in data]

【讨论】:

  • 如果您有一些不同格式的浮点数(例如 5.2456e10),这将失败。按照 cmets 的建议,更好地使用 Python 的内置解析器来评估字符串中的 Python 表达式。
  • 未提及特殊格式,但感谢您的建议。
  • 它是否适用于 5.2456e-10、5.2456e+9、-5.2456e-10、.1、1.?
  • 是的,现在确实如此,但我相信您会找到另一个案例 ;-) Deutsche Korrektheit 是?
  • 我发现user3387223的建议非常重要,所以我再次改进了解决方案以允许负值。
猜你喜欢
  • 1970-01-01
  • 2017-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
相关资源
最近更新 更多