【发布时间】:2013-11-26 16:38:29
【问题描述】:
我想制作一个 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 2 还是 3?
-
Python 2.7.3 实际上:)
-
您必须在正则表达式中使用原始 unicode 字符串以及 re.U 标志才能使其工作。
-
@alko:
re.U标志在为正则表达式使用unicode字符串值时是隐含的。 -
面面相觑的回答 - 使用 Python 3.x 来避免 unicode 问题。
标签: python regex unicode python-unicode