【发布时间】:2022-11-07 16:56:20
【问题描述】:
我正在尝试解析大量文件,其中的记录包括西班牙语日期,格式类似于“Ago 01, 2022”。对于这个任务,我使用来自dataparser 模块的函数parse。过去,我可以成功地将该函数用于类似目的,但现在即使我为 parse 函数设置语言或区域设置参数,它也会以西班牙语显示字符串失败。
我用这一行导入函数parse:
from dateparser import parse
- 如果我用英文日期调用该函数,它将成功运行,正如我所料:
parse('Aug 01, 2021', date_formats=['%b %d, %Y'] ) # Returns datetime.datetime(2022, 8, 1, 0, 0)-
如果我在没有任何其他参数的情况下使用西班牙语日期调用该函数,它将无法成功运行,正如我所期望的那样:
(八月西班牙语是阿戈斯托):
parse('Ago 01, 2021', date_formats=['%b %d, %Y'] ) # Raises an exception in regex that ends with: ~\anaconda3\lib\site-packages\regex\_regex_core.py in _compile_replacement(source, pattern, is_unicode) 1735 return False, [value] 1736 -> 1737 raise error("bad escape \\%s" % ch, source.string, source.pos) 1738 1739 if isinstance(source.sep, bytes): error: bad escape \d at position 7我想这个错误与西班牙语的正则表达式模式有关,但我不能确定语言之外的问题是什么。
- 给
parse一个语言参数不会改变结果。
parse('Ago 01, 2021', date_formats=['%b %d, %Y'], languages=['es']) # Raises the same exception that ends with: ~\anaconda3\lib\site-packages\regex\_regex_core.py in _compile_replacement(source, pattern, is_unicode) 1735 return False, [value] 1736 -> 1737 raise error("bad escape \\%s" % ch, source.string, source.pos) 1738 1739 if isinstance(source.sep, bytes): error: bad escape \d at position 7- 如果我设置参数区域设置,会出现类似的情况。
parse('Ago 01, 2021', date_formats=['%b %d, %Y'], locales=['es']) # Raises the same exception that ends with: ~\anaconda3\lib\site-packages\regex\_regex_core.py in _compile_replacement(source, pattern, is_unicode) 1735 return False, [value] 1736 -> 1737 raise error("bad escape \\%s" % ch, source.string, source.pos) 1738 1739 if isinstance(source.sep, bytes): error: bad escape \d at position 7
我不确定问题是否与模块的更新或更改有关,但我想提一下,当我第一次致电
parse时,我收到了此警告消息。~\anaconda3\lib\site-packages\dateparser\utils\__init__.py:130: PytzUsageWarning: The localize method is no longer necessary, as this time zone supports the fold attribute (PEP 495). For more details on migrating to a PEP 495-compliant implementation, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html date_obj = tz.localize(date_obj)为了寻找见解,我尝试使用位于此 URL https://dateparser-demo.netlify.app/ 中的
dateparser的演示,在此 github 的存储库中引用 https://github.com/scrapinghub/dateparser 在 PyPi https://pypi.org/project/dateparser/ 中引用。但是,在这个演示中,我的西班牙语字符串被成功解析。我想我有一个旧版本的 dateparser,所以我检查了一下,我在 PyPi 中有最新版本。- 我在一台装有西班牙文 Windows 10 的机器上使用
python3.7.3 和dateparser1.1.1(目前是最新版本)。
-
【问题讨论】:
-
值得一提的是:我使用 Python 3.7.13 和 dateparser 1.1.1 在 macOS(英语)上运行了您的示例 1 和 3,没有出现错误。虽然我确实收到了
PytzUsageWarning,但到目前为止这只是一个警告。结果日期是正确的。让我想知道 Windows 是否应该归咎于此。 -
PyPI 页面上的示例没有显示任何使用
date_formats参数。由于错误提到了\b,并且格式中有%b,您可以尝试不使用:parse('Ago 01, 2021', languages=['es'])吗? -
显然相关:github.com/scrapinghub/dateparser/issues/1052。似乎在 github.com/scrapinghub/dateparser/pull/1067 中建议了一个修复程序,但这还没有,而且还远远超过了 1.1.1 的发布。
-
鉴于 GitHub 问题中的 cmets,您可以尝试将
regex模块降级几个(次要)版本。我不能告诉你到底是哪一个,因为内部版本与 PyPI 上的不匹配,所以虽然我的本地正则表达式版本不是最新的(并且工作正常),但我不知道它是哪个 PyPI 版本.
标签: python python-3.x datetime dateparser