python:从文本文件创建字典:输入短文本并返回长文本

2024-06-08 17:10:44 发布

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

文件“Textese.txt”包含一个单词及其到Textese的翻译。我需要写一个程序来创建一个带有该文件的字典,要求用户输入一个简单的句子,然后将其翻译成textese

例如,输入'b4',程序应返回'before'。我知道我需要使用define函数和translate方法,但我不知道如何将其组合起来

该文件看起来像:

before,b4
busy,bz
computer,puter
definitely,def
easy,ez
energy,nrg
enjoy,njoy
enough,nuff
everyone,every1
excellent,xlnt
favorite,fav

Tags: 文件方法函数用户程序txt字典单词
3条回答

好吧,如果这是你的文件的格式,在我看来,每个单词/翻译对用逗号分隔,每个对用换行符(或多个换行符)与其他对分隔。您可以将文件中的数据读入单个字符串,然后使用yourstring.split("\n")获得一个列表,其中每个元素的格式为“word,textese”,然后循环遍历这些元素中的每个元素并再次拆分,这次使用逗号作为分隔符(element.split(","))。如果您想知道如何将每个单词及其相关翻译转换为“键值”词典,请阅读this

首先需要将这些对转换为dictionarykey/value对:

with open('test.txt', 'r') as f:
    output = f.read().splitlines()

converter_dict = {each_word.split(',')[1]: each_word.split(',')[0] for each_word in output}
# -> {'b4': 'before', 'bz': 'busy', 'puter': 'computer', ...}

获取user_input后,您可以将输入拆分为单词,并检查字典中是否有任何匹配的key/value对:

# assuming user input will always be separated by space
user_input = "def nuff nrg"
words = user_input.split()
# -> ['def', 'nuff', 'nrg']

# Get value of each word from dict if it exists, else return None
result = [converter_dict.get(word, None) for word in words]
# -> ['definitely', 'enough', 'energy']

最后,您需要将该列表转换为单个字符串:

# Convert list of words into a single string
sentence = ' '.join(result)
# -> 'definitely enough energy'

您可以对此类程序使用tkinter。假设您的data.txt如下所示:

efore,b4
busy,bz
computer,puter
definitely,def
easy,ez
energy,nrg
enjoy,njoy
enough,nuff
everyone,every1
excellent,xlnt

代码:

import tkinter as tk

class App(object):
    def __init__(self):

        self.dictionary = {}
        with open('data.txt', 'r') as f:
            for line in f.read().rstrip().split('\n'):
                value, key = line.split(',')
                self.dictionary[key] = value

        self.root = tk.Tk()
        self.entry = tk.Entry(self.root)
        self.entry.pack()
        self.btn = tk.Button(self.root, text='Translate', command=self.translate)
        self.btn.pack()
        self.lbl = tk.Label(self.root)
        self.lbl.pack()
        self.root.mainloop()

    def translate(self):
        result = self.dictionary.get(self.entry.get())
        if result:
            self.lbl.configure(text=result)
        else:
            self.lbl.configure(text='Translation not found')

App()

输出:

enter image description here

基于命令行的脚本:

dictionary = {}
with open('data.txt', 'r') as f:
    for line in f.read().rstrip().split('\n'):
        value, key = line.split(',')
        dictionary[key] = value

word = input('Enter word: ')
result = dictionary.get(word)
if result:
    print(result)
else:
    print('Translation not found')

输出:

Enter word: ez
easy

相关问题 更多 >