Kin*_*ber -2 python regex python-3.5
import os\nimport codecs\nimport argparse\nos.chdir(\'C:\\\\Users\\\\Kingsaber\\\\Desktop\\\\python_excercises\')\na = codecs.open(\'BeforeKichiku.txt\', encoding=\'utf-8\')\np = a.read()\nprint(p)\n\nimport re\n\n#ch = u"I am from \xe7\xbe\x8e\xe5\x9b\xbd\xe3\x80\x82We should be friends. \xe6\x9c\x8b\xe5\x8f\x8b."\n\nb = re.findall(u"[\\u4e00-\\u9fff]+", a)\nfor x in b:\n print(x)\nRun Code Online (Sandbox Code Playgroud)\n\n预期结果:打印出变量“a”中的所有内容,并找到 u4e00-\\u9fff 之间的所有 unicode 字符并在下面打印出来。
\n\n发生了什么:文档成功打印出来,但正则表达式搜索出现以下错误。如果我切换正则表达式来搜索字符串“ch”,一切都会按预期工作。由于某种原因,它不适用于 Unicode 文档。
\n\n错误:
\n\nTraceback (most recent call last):\n File "C:/Users/Kingsaber/Desktop/destruga3.py", line 15, in <module>\n b = re.findall(u"[\\u4e00-\\u9fff]+", a)\n File "C:\\Users\\Kingsaber\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\re.py", line 213, in findall\n return _compile(pattern, flags).findall(string)\nTypeError: expected string or bytes-like object\nRun Code Online (Sandbox Code Playgroud)\n
根据错误:
expected string or bytes-like object
Run Code Online (Sandbox Code Playgroud)
您只需使用 str() 将后面的部分作为字符串类型的数据传输即可:
b = re.findall(u"[\u4e00-\u9fff]+", str(a))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17427 次 |
| 最近记录: |