读出基于文本文件的字典的定义

时间:2015-10-24 09:41:52

标签: python dictionary

我试图编写一个Python函数,它将基于文本文件的字典作为输入,例如Webster的免费字典。功能" webster_definition"然后,将搜索文本文件并打印特定单词的定义,例如"加拿大"

这是我到目前为止所得到的:

import re
import sys

def webster_definition(word):
    word = word.upper()
    output = ""
    doc = open("webster.txt",'r')           

    for line in doc:     
        if re.match(word,line):
            print line

    return output

print webster_definition("Canada")

这将输出我查找的单词。但是这个定义后来用" Defn开始三行:"并且长度可变,例如:

CANADA
Can"a*da, n.

Defn: A British province in North America, giving its name to various
plants and animals. Canada balsam. See under Balsam.
 -- Canada goose. (Zoöl.) See Whisky Jack.
 -- Canada lynx. (Zoöl.) See Lynx.
 -- Canada porcupine (Zoöl.) See Porcupine, and Urson.
 -- Canada rice (Bot.) See under Rick.
 -- Canada robin (Zoöl.), the cedar bird.

所需的输出应如下所示:

CANADA
Defn: A British province in North America, giving its name to various
plants and animals. Canada balsam. See under Balsam.
 -- Canada goose. (Zoöl.) See Whisky Jack.
 -- Canada lynx. (Zoöl.) See Lynx.
 -- Canada porcupine (Zoöl.) See Porcupine, and Urson.
 -- Canada rice (Bot.) See under Rick.
 -- Canada robin (Zoöl.), the cedar bird.

任何人都可以帮我解释定义的输出吗?

4 个答案:

答案 0 :(得分:0)

在档案中:

CANADA
Can"a*da, n.

Defn: A British province in North America, giving its name to various
plants and animals. Canada balsam. See under Balsam.
 -- Canada goose. (Zoöl.) See Whisky Jack.
 -- Canada lynx. (Zoöl.) See Lynx.
 -- Canada porcupine (Zoöl.) See Porcupine, and Urson.
 -- Canada rice (Bot.) See under Rick.
 -- Canada robin (Zoöl.), the cedar bird.

 ANOTHER DEFENITION
 another defenition

 Defn.. some words
 more words
 ......


with open('webster_file', 'r') as f:
     # read into a string.
     data = f.read()

# uppercase word to search for
word = 'canada'.upper()
# search for empty line and the get everything non-greedy up to the 
# another empty line.
pattern = '^' + word + '.*?\n^$\n.*?^$'

mo = re.search(pattern,data,re.M|re.DOTALL)

if mo:
    print(mo.group(0))


CANADA
Can"a*da, n.

Defn: A British province in North America, giving its name to various
plants and animals. Canada balsam. See under Balsam.
 -- Canada goose. (Zoöl.) See Whisky Jack.
 -- Canada lynx. (Zoöl.) See Lynx.
 -- Canada porcupine (Zoöl.) See Porcupine, and Urson.
 -- Canada rice (Bot.) See under Rick.
 -- Canada robin (Zoöl.), the cedar bird

答案 1 :(得分:0)

我不确定我是否完全跟随。

但是如果你不想打印空行,你可以检查它并不打印它们,例如:

if line in ['\n', '\r\n', '']:
    continue
print line

答案 2 :(得分:0)

# coding: utf-8

data = '''CANADA
Can"a*da, n.

Defn: A British province in North America, giving its name to various
plants and animals. Canada balsam. See under Balsam.
 -- Canada goose. (Zoöl.) See Whisky Jack.
 -- Canada lynx. (Zoöl.) See Lynx.
 -- Canada porcupine (Zoöl.) See Porcupine, and Urson.
 -- Canada rice (Bot.) See under Rick.
 -- Canada robin (Zoöl.), the cedar bird.'''

data = data.split('\n\n')
data = [data[0].split('\n')[0]] + [data[1]]
data = '\n'.join(data)

答案 3 :(得分:0)

通常有助于将任务分解为更简单的功能。对于文本文件解析的情况,生成器非常方便:

def read_paragraph(fp):
    """ 
    Read lines from the file until the end of the paragraph 
    """
    while True:
        line = fp.readline()
        if not line.strip():
            break
        yield line

def skip_paragraph(fp):
    while fp.readline().strip():
        pass

def find_definition(fp, word):
    word = word.upper()
    while True:
        line = fp.readline()
        if not line:
            break  # end of file, consider raising an exception here

        if line.strip() == word:
            yield line          # found the word
            skip_paragraph(fp)  # move to the definition
            for defline in read_paragraph(fp):
                yield defline
            break
        else:
            # we're not interested in the current word, just skipping it
            skip_paragraph(fp)
            skip_paragraph(fp)

最后,得到一个定义:

with open('webster.txt') as fp:
    definition = find_definition(fp, 'Canada')
    print ''.join(definition)

也就是说,如果你需要经常查询字典,并且性能有任何问题,可以考虑将文本文件转换为sqlite数据库。

相关问题