正则表达式搜索需要的字符串或类似字节的对象

2024-04-27 02:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

import os
import codecs
import argparse
os.chdir('C:\\Users\\Kingsaber\\Desktop\\python_excercises')
a = codecs.open('BeforeKichiku.txt', encoding='utf-8')
p = a.read()
print(p)

import re

#ch = u"I am from 美国。We should be friends. 朋友."

b = re.findall(u"[\u4e00-\u9fff]+", a)
for x in b:
    print(x)

预期结果:在变量“a”中打印所有内容,并在u4e00-\u9fff之间找到所有unicode字符,然后在下面打印出来。

发生了什么:文档打印成功,但regex搜索会出现以下错误。如果我切换regex来搜索字符串“ch”,一切都会正常工作。出于某种原因,它不能处理Unicode文档。

错误:

Traceback (most recent call last):
  File "C:/Users/Kingsaber/Desktop/destruga3.py", line 15, in <module>
    b = re.findall(u"[\u4e00-\u9fff]+", a)
  File "C:\Users\Kingsaber\AppData\Local\Programs\Python\Python35-32\lib\re.py", line 213, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object

Tags: in文档importreoschusersregex