【发布时间】:2014-10-15 18:24:06
【问题描述】:
当下一行以小写字符开头时,我想用空格替换换行符。
我的 Python 3.3 代码在下一行以 [a-z] 开头时工作,但如果它以(小写)Unicode 字符开头则失败。
Test file (saved as UTF-8): Test to check<CRLF>whether it's working.<CRLF>Aquela é<CRLF>árvore pequena.<CRLF>
import os
input_file = 'test.txt'
input_file_path = os.path.join("c:", "\\", "Users", "Paulo", "workspace", "pdf_to_text", input_file)
input_string = open(input_file_path).read()
print(input_string)
import re
pattern = r'\n([a-zàáâãäåæçčèéêëěìíîïłðñńòóôõöøőřśŝšùúûüůýÿżžÞ]+)'
pattern_obj = re.compile(pattern)
replacement_string = " \\1"
output_string = pattern_obj.sub(replacement_string, input_string)
print(output_string)`
【问题讨论】:
-
测试文件的编码是什么?
-
""应该在pattern =行上做什么? -
另外,为什么要硬编码这个特定的小写字母子集,而不是使用 Unicode 字符类别
Ll或适当的语言环境概念? -
最重要的是:您能给我们一些示例输入数据吗?最简单的方法是给我们一个MCVE,它有
input_string = "<some constant that demonstrates the problem>"来代替从我们没有的文件中加载它的代码。 -
另外,您确定您的文本编辑器将此源代码保存为 UTF-8 而不是其他编码吗?你在 Windows 上,许多 Windows 编辑器默认使用不同的东西。
标签: python regex python-3.x unicode