3

我想制作一个 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_oti, regex_tis, regex_ton) 不匹配任何内容,因此我创建的 3 个文本文件不包含任何内容。

也许它是一个编码问题(Unicode)?

4

1 回答 1

1

您正在尝试将编码值(作为字节)与一个正则表达式进行匹配,除非您的 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可迭代对象(无需一次将所有行读入内存),并预编译正则表达式。

于 2013-11-13T21:38:06.667 回答