繁体   English   中英

用Unicode字符替换Python 3.x

[英]Python 3.x replacements with Unicode characters

当下一行以小写字符开头时,我想用空格替换换行符。

当下一行以[az]开头时,我的Python 3.3代码正常工作,但如果以(小写)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)`

...当我读取文件时,原始文件中的Unicode字符é和á分别更改为é和á。

您的实际问题与正则表达式无关。 您正在使用不正确的latin-1编码读取utf-8文本。

>>> print("é".encode('utf-8').decode('latin-1'))
é
>>> print("á".encode('utf-8').decode('latin-1'))
á

要读取utf-8文件:

with open(filename, encoding='utf-8') as file:
    text = file.read()

关于正则表达式的旧答案(与OP问题无关):

通常,单个用户可感知的字符(例如çé可能会跨越多个Unicode代码点,因此[çé]可能会分别匹配这些Unicode代码点,而不是匹配整个字符。 (?:ç|é)将解决此问题,还有其他问题,例如Unicode规范化(NFC,NFKD)。

当下一行以小写字符开头时,我想用空格替换换行符。

regex模块支持POSIX字符类[:lower:]

import regex # $ pip install regex

text = ("Test to check\n"
        "whether it's working.\n"
        "Aquela \xe9\n"
        "\xe1rvore pequena.\n")
print(text)
# -> Test to check
# -> whether it's working.
# -> Aquela é
# -> árvore pequena.
print(regex.sub(r'\n(?=[[:lower:]])', ' ', text))
# -> Test to check whether it's working.
# -> Aquela é árvore pequena.

要使用re模块模拟[:lower:]类:

import re
import sys
import unicodedata

# \p{Ll} chars
lower_chars = [u for u in map(chr, range(sys.maxunicode)) 
               if unicodedata.category(u) == 'Ll']
lower = "|".join(map(re.escape, lower_chars))
print(re.sub(r"\n(?={lower})".format(lower=lower), ' ', text))

结果是一样的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM