如何在Python中正确使用正则表达式中的汉字?

1 投票
1 回答
1111 浏览
提问于 2025-04-18 01:10

我在使用Windows 7和Python 3.3,命令提示符的编码页面是936。

>>> import re
>>> if(re.search(r"仟|佰|千|百","百万")):print("ok1")
...
ok1
>>> if(re.search(u"仟|佰|千|百","百万")):print("ok2")
...
ok2

我把代码保存在g:\test_number.py这个文件里。

# -*- coding: utf-8 -*- 
import re
if(re.search(r"仟|佰|千|百","百万")):print("ok1")
if(re.search(u"仟|佰|千|百","百万")):print("ok2")

然后我运行这个命令 python g:\\test_number.py,结果出现了错误:

C:\Windows\system32\cmd.exe /c (python \test_number.py)
File "\test_number.py", line 3
SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xb0 in position 3:
 invalid start byte
shell returned 1
Hit any key to close this window...

这是怎么回事呢? 我修改了代码,结果还是同样的错误。

# -*- coding: utf-8 -*- 
import re
output=open("g://number","w",encoding="utf-8")
if(re.search(r"仟|佰|千|百","百万")):output.write("ok1")
if(re.search(u"仟|佰|千|百","百万")):output.write("ok2")
output.close()

在这里输入图片描述

1 个回答

2

确保你的编辑器设置为使用utf-8编码来保存文件。

在这里输入图片描述

撰写回答