在文件中查找单词,返回定义



我正在制作一个小型字典应用程序,只是为了学习Python。我有添加单词的功能(只需要添加检查以防止重复),但我正在尝试创建查找单词的功能。

这是我将单词附加到文本文件时的文本文件的外观。

{word|Definition}

我可以通过这样做来检查这个词是否存在,

if word in open("words/text.txt").read():

但是我如何获得定义呢?我想我需要使用正则表达式(这就是为什么我将其拆分并放在大括号内的原因),我只是不知道如何。

read()将读取整个文件内容。您可以改为这样做:

for line in open("words/text.txt", 'r').readlines():
    split_lines = line.strip('{}').split('|')
    if word == split_lines[0]: #Or word in line would look for word anywhere in the line
        return split_lines[1]

如果你想要有效的搜索,你可以使用字典。

with open("words/text.txt") as fr:
    dictionary = dict(line.strip()[1:-1].split('|') for line in fr)
print(dictionary.get(word))

还要尽量避免使用如下语法:

if word in open("words/text.txt").read().

使用上下文管理器(with语法)来确保关闭该文件。

获取所有定义

f = open("words/text.txt")
for line in f:
  print f.split('|')[1]

最新更新