python regex unicode - 从 utf-8 文件中提取数据

标签 python regex unicode extract

我在从包含中文字符的 UTF-8 文件中提取数据时遇到困难。

该文件实际上是 CEDICT(汉英词典),如下所示:

賓 宾 [bin1] /visitor/guest/object (in grammar)/
賓主 宾主 [bin1 zhu3] /host and guest/
賓利 宾利 [Bin1 li4] /Bentley/
賓士 宾士 [Bin1 shi4] /Taiwan equivalent of 奔馳|奔驰[Ben1 chi2]/
賓夕法尼亞 宾夕法尼亚 [Bin1 xi1 fa3 ni2 ya4] /Pennsylvania/
賓夕法尼亞大學 宾夕法尼亚大学 [Bin1 xi1 fa3 ni2 ya4 Da4 xue2] /University of Pennsylvania/
賓夕法尼亞州 宾夕法尼亚州 [Bin1 xi1 fa3 ni2 ya4 zhou1] /Pennsylvania/

直到现在,我设法使用 split() 获得了前两个字段,但我无法找到我应该如何继续提取其他两个字段(假设第二行“bin1 zhu3”和“host and客人”。我一直在尝试使用正则表达式,但由于我忽略的原因它不起作用。

#!/bin/python
#coding=utf-8
import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)

def look(character):
    myFile = open("/home/quentin/cedict_ts.u8","r")
    for line in myFile:
        line = line.rstrip()
        elements = line.split(" ")
        try:
            if line != "" and elements[1] == character:
                myFile.close()
                return line
        except:
            myFile.close()
            break
    myFile.close()
    return "Aucun résultat :("


translation = look("賓主") # translation contains one line of the file
elements = translation.split()
traditionnal = elements[0]
simplified = elements[1]
print "Traditionnal:" + traditionnal
print "Simplified:" + simplified

m = REMatcher(translation)
tr = ""
if m.match(r"\[(\w+)\]"):
    tr = m.group(1) 
print "Pronouciation:" + tr

感谢任何帮助。

最佳答案

这会构建一个字典来查找简体字或繁体字的翻译,并在 Python 2.7 和 3.3 中工作:

# coding: utf8
import re
import codecs

# Process the whole file decoding from UTF-8 to Unicode
with codecs.open('cedict_ts.u8',encoding='utf8') as datafile:
    D = {}
    for line in datafile:
        # Skip comment lines
        if line.startswith('#'):
            continue
        trad,simp,pinyin,trans = re.match(r'(.*?) (.*?) \[(.*?)\] /(.*)/',line).groups()
        D[trad] = (simp,pinyin,trans)
        D[simp] = (trad,pinyin,trans)

输出(Python 3.3):

>>> D['马克']
('馬克', 'Ma3 ke4', 'Mark (name)')
>>> D['一路顺风']
('一路順風', 'yi1 lu4 shun4 feng1', 'to have a pleasant journey (idiom)')
>>> D['馬克']
('马克', 'Ma3 ke4', 'Mark (name)')

输出(Python 2.7,您必须打印字符串才能看到非 ASCII 字符):

>>> D[u'马克']
(u'\u99ac\u514b', u'Ma3 ke4', u'Mark (name)')
>>> print D[u'马克'][0]
馬克

关于python regex unicode - 从 utf-8 文件中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20859981/

相关文章:

python - 如何将unicode字符串拆分为列表

python - 向装饰器添加参数会删除 cls 参数

javascript - 在 javascript 中查找正则表达式电话号码并将其替换为可调用链接

regex - 使用正则表达式搜索文本以匹配外部特定字符

PHP preg_match 部分 url

objective-c - objective-c 中的 unicode 转义

c++ - 如何通过指针读取 UTF-8 字符?

python - 使用 Pisa/xhtml2pdf 在 Python 中创建 pdf

python - PyCharm 找不到 Spacy 模型 'en'

python - 使用 Django 下载 xlsx 格式的 SQL 数据