numpy-loadtxt和使用转换器进行日期

问题描述:

我要加载具有以下格式的txt:

I want to load a txt which has the following formatting:

20-Sep-13,178.90,185.83,178.56,183.39,13401689
19-Sep-13,170.80,180.47,169.08,177.92,15594568
18-Sep-13,167.07,167.45,164.20,166.22,5439615
17-Sep-13,165.08,168.42,163.36,166.23,5500719

因此,我使用以下Python行:

Therefor I use the following Python line:

date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile, delimiter=',', unpack=True, converters={0: mdates.strpdate2num('%d-%b-%y')})

但是出现以下错误:

failed main loop time data '\xef\xbb\xbf20-Sep-13' does not match format '%d-%b-%y'

有人知道我在做什么错吗?

Does anyone know, what I'm doing wrong?

Thx, 梅奇

文本文件包含UTF-8 BOM字符. numpy.loadtxt 不接受encoding,但是您可以传递iterable而不是文件名.

The text file contain UTF-8 BOM characters. numpy.loadtxt does not accept encoding, but you can pass iterable instead of filename.

尝试以下操作:

stockFile = '....'


import numpy as np
import matplotlib.dates as mdates
import codecs

with codecs.open(stockFile, encoding='utf-8-sig') as f:
    date, closep, highp, lowp, openp, volume = np.loadtxt(f, delimiter=',', unpack=True, converters={0: mdates.strpdate2num('%d-%b-%y')})