读取包含英语词典的文本文件以在python中打印匹配的词义

2024-05-16 00:20:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,里面有一本英语词典,上面列出了如下单词:

Zymome (n.) A glutinous substance, insoluble in alcohol, resembling legumin;         -- 
now called vegetable fibrin, vegetable albumin, or gluten casein.

Zymometer (n.) Alt. of Zymosimeter

Zymophyte (n.) A bacteroid ferment.

正如你所看到的,意思是多行的。有人能帮我用一个程序在文本文件的输入中搜索这个词,并显示这个词的相应含义吗?你知道吗

我试过的代码:

x=raw_input("Enter word: ")
with open('e:\\Python27\\My programs\\dictionary.txt') as file:    
    data = file.readlines()
    for line in data:
        if x in line:
            print line

谢谢!你知道吗


Tags: indataline单词英语词典file文本文件substance
1条回答
网友
1楼 · 发布于 2024-05-16 00:20:12

我想这就是你想要的:

x = raw_input("Enter word: ")
with open('dictionary.txt') as file:
    data = file.read()

x_pos = data.find(x)
meaning= None
if x_pos == 0 or (x_pos != -1 and data[x_pos - 1] == '\n' and data[x_pos - 2] == '\n'):
    i = x_pos
    while i < len(data):
        if data[i] == '\n' and i > 0 and data[i - 1] == '\n':
            break
        meaning += data[i]
        i += 1

print meaning if meaning else "Not found"

或基于regex的解决方案:

import re


x = raw_input("Enter word: ").strip()
with open('d.txt') as file:
    data = '\n\n' + file.read() + '\n\n'

pattern = r'\n\n(' + x + r' .*?)\n\n'
pattern_compiled = re.compile(pattern, re.DOTALL)

res = pattern_compiled.search(data)
if res:
    print(res.group(1))
else:
    print('Not found')

相关问题 更多 >