【问题标题】:Why my RegEx pattern in Unicode does not work?为什么我的 Unicode 正则表达式模式不起作用?
【发布时间】:2020-04-02 05:50:35
【问题描述】:
import re
file = open('C:\item.bh.txt', 'r', encoding = 'utf-16')
pattern = re.findall(ur'[\u09ac][\u0995]', file)

它显示以下错误:

File "<ipython-input-22-bbd94837f9ee>", line 1
pattern = re.findall(ur'[\u09ac][\u0995]', file)
                                           ^
SyntaxError: invalid syntax

【问题讨论】:

  • 你在使用 Python 2 吗?
  • 我正在使用 python 3
  • @MaumitaBhaumik 由于以下答案对您有用,请考虑将其标记为已接受。

标签: python python-3.x regex unicode


【解决方案1】:

这里有一个原始的 unicode 字符串是没有意义的,因为您希望转义序列被解释。第二个re.findall 接受一个字符串,而不是一个文件,所以你必须读取文件。也不需要字符类,因为它们只包含一个字符。

re.findall(u'\u09ac\u0995', file.read())

或者在上下文中:

import re
file = open(r'C:\item.bh.txt', 'r', encoding = 'utf-16')
pattern = re.findall(u'\u09ac\u0995', file.read())

【讨论】:

  • 导入 re 文件 = open('C:\item.bh.txt', 'r', encoding = 'utf-16') 模式 = re.findall(u'\u09ac\u0995' , file.read()) 这种语法也给我一个错误
  • UnicodeDecodeError: 'utf-16-le' codec can't decode byte 0x0a in position 315564: truncated data
  • 以上答案是针对 Python 2 的。对于 Python 3,只需去掉开头的 u 前缀即可。
  • 可能还会加倍反斜杠,或者切换到路径的原始字符串。它恰好适用于\i,但会因\n\a 等而中断。
  • 除非您更改了输入文件,否则“截断数据”错误仍应重现。它表明文件的内容已损坏,或者实际上不是 UTf-16(尽管在文件中很远,可能是前者)。
猜你喜欢
  • 2013-09-08
  • 2012-11-17
  • 2012-08-07
  • 1970-01-01
  • 2015-04-13
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多