我想制作一个 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)?
最佳答案
您正在尝试将编码值(字节)与正则表达式匹配,很可能除非您的 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/