用于希腊语单词的 Python 正则表达式

标签 python regex unicode python-unicode

我想制作一个 python 脚本,它使用正则表达式从我提供的源文本中过滤出包含某些希腊单词的行,然后根据遇到的单词将这些行写入 3 个不同的文件。

到目前为止,这是我的代码:

import regex

source=open('source.txt', 'r')
oti=open('results_oti.txt', 'w')
tis=open('results_tis.txt', 'w')
ton=open('results_ton.txt', 'w')

regex_oti='^.*\b(ότι|ό,τι)\b.*$'
regex_tis='^.*\b(της|τις)\b.*$'
regex_ton='^.*\b(τον|των)\b.*$'

for line in source.readlines():
    if regex.match(regex_oti, line):
        oti.write(line)
    if regex.match(regex_tis, line):
        tis.write(line)
    if regex.match(regex_ton, line):
        ton.write(line)
source.close()
oti.close()
tis.close()
ton.close()
quit()

我检查的词是 óτι | ω,τι | της | τις | τον | των.

问题是这 3 个正则表达式(regex_otiregex_tisregex_ton)不匹配任何东西,所以我创建的 3 个文本文件不包含任何东西。

可能是编码问题 (Unicode)?

最佳答案

您正在尝试将编码值(字节)与正则表达式匹配,很可能除非您的 Python 源编码与输入文件的编码完全匹配,并且只有当您未使用 UTF-8 等多字节编码。

您需要将输入文件解码为 Unicode 值,并使用 Unicode 正则表达式。这意味着您需要知道用于输入文件的编解码器。用起来最简单 io.open()处理解码和编码:

import io
import re

regex_oti = re.compile(ur'^.*\b(ότι|ό,τι)\b.*$')
regex_tis = re.compile(ur'^.*\b(της|τις)\b.*$')
regex_ton = re.compile(ur'^.*\b(τον|των)\b.*$')

with io.open('source.txt', 'r', encoding='utf8') as source, \
     io.open('results_oti.txt', 'w', encoding='utf8') as oti, \
     io.open('results_tis.txt', 'w', encoding='utf8') as tis, \
     io.open('results_ton.txt', 'w', encoding='utf8') as ton:

    for line in source:
        if regex_oti.match(line):
            oti.write(line)
        if regex_tis.match(line):
            tis.write(line)
        if regex_ton.match(line):
            ton.write(line)

注意 ur'...' 原始 unicode 字符串来定义正则表达式模式;现在这些是 Unicode 模式并匹配代码点,而不是字节。

io.open() 调用确保您读取 unicode,并且当您将 unicode 值写入输出文件时,数据自动编码为 UTF-8。我也为输入文件选择了 UTF-8,但您需要检查该文件的正确编解码器是什么并坚持使用。

我在这里使用了一个 with 语句让文件自动关闭,使用 source 作为一个可迭代的(不需要一次将所有行读入内存) , 并预编译了正则表达式。

关于用于希腊语单词的 Python 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19964608/

相关文章:

regex - 使用 vim 搜索和替换将 JSON 字段名称括在引号中

python - 将文本文件中的 ascii 字符转换为 Unicode

python - 当 python 程序不在前台时,如何读取击键?

python - 如何解决这个问题(Pytorch RuntimeError : 1D target tensor expected, multi-target not supported)

regex - Scala:如何构造一个包含变量的正则表达式?

python - 旧的 UnicodeEncodeError 打印结果来自使用 adodbapi 的 MS SQL 查询

python - python 正则表达式的 UnicodeDecodeError

python - 在 Matplotlib 图中从 Pandas Dataframe 注释点

python - 通过 +-*/() (作为分隔符)分割线而不在 python 中省略它们

regex - .NET 的 URL 解析 PCRE 正则表达式的等价物