【问题标题】:Python function returns empty list when string variable is passed传递字符串变量时,Python函数返回空列表
【发布时间】:2017-08-25 18:57:06
【问题描述】:

我正在开发一个自动完成文本编辑器。当按下空格时,它会从用户那里获取输入,并打印用户提到的带有前缀的单词列表。

代码如下:

#!/usr/bin/env python

from tkinter import *
import tkinter.font as tkFont


class Node:
    def __init__(self):
        self.word = None
        self.nodes = {}  # dict of nodes

    def __get_all__(self):
        x = []

        for key, node in self.nodes.items():
            if (node.word is not None):
                x.append(node.word)

            x = x + node.__get_all__

        return x

    def __str__(self):
        return self.word

    def __insert__(self, word, string_pos=0):
        current_letter = word[string_pos]

        if current_letter not in self.nodes:
            self.nodes[current_letter] = Node();
        if (string_pos + 1 == len(word)):
            self.nodes[current_letter].word = word
        else:
            self.nodes[current_letter].__insert__(word, string_pos + 1)

            return True

    def __get_all_with_prefix__(self, prefix, string_pos):
        x = []
        #print("We are in the get prefix func", prefix)

        for key, node in self.nodes.items():
            if (string_pos >= len(prefix) or key == prefix[string_pos]):
                if (node.word is not None):
                    x.append(node.word)

                if (node.nodes != {}):
                    if (string_pos + 1 <= len(prefix)):
                        x = x + node.__get_all_with_prefix__(prefix, string_pos + 1)
                    else:
                        x = x + node.__get_all_with_prefix__(prefix, string_pos)

        return x


class Trie:
    def __init__(self):
        self.root = Node()

    def insert(self, word):
        self.root.__insert__(word)

    def get_all(self):
        return self.root.__get_all__

    def get_all_with_prefix(self, prefix, string_pos=0):
        return self.root.__get_all_with_prefix__(prefix, string_pos)


root = Tk()
trie = Trie()
customFont = tkFont.Font(family="arial", size=17)

with open('words_file_for_testing.txt', mode='r') as f:
    for line in f:
        for word in line.split():
            trie.insert(word)


def retrieve_input(self):
    inputValue = content_text.get("1.0", "end-1c")
    print(trie.get_all_with_prefix(inputValue))
    printing_the_list(inputValue)

def printing_the_list(getinputvalue):
    print(getinputvalue)
    print(type(getinputvalue))
    print(trie.get_all_with_prefix("A"))
    print(trie.get_all_with_prefix(getinputvalue))
    #print(type(words))
    #print(words)
    #print(trie.get_all_with_prefix("A"))
    #master = Tk()
    #listbox = Listbox(master)
    #listbox.pack()
    #for item in words:
    # listbox.insert(END, item)

root.title("Autocomplete Word")
root.geometry('800x400+150+200')
content_text = Text(root, wrap='word', font=customFont)
content_text.focus_set()
content_text.pack(expand='yes', fill='both')
scroll_bar = Scrollbar(content_text)
content_text.configure(yscrollcommand=scroll_bar.set)
scroll_bar.config(command=content_text.yview)
scroll_bar.pack(side='right', fill='y')
root.bind("<space>", retrieve_input)
root.mainloop()

现在,我的printing_the_list(getinputvalue) 函数有问题。在此函数中,getinputvalue 是存储用户输入值的变量。当我手动将字符串输入到print(trie.get_all_with_prefix("A")) 函数时,它会根据需要打印单词列表,但是当我尝试使用getinputvalue 变量打印具有用户输入值的单词前缀列表时,得到一个空列表为[]

上面的python代码打印:

[]
A 
<class 'str'>
['AAE', 'AAEE', 'AAG', 'AAF', 'AAP', 'AAPSS', 'AAM', 'AAMSI', 'AARC', 'AAII', 'AAO', 'Aar', 'Aaron', 'Aarika', 'Aargau', 'Aaren', 'Aarhus', 'Aara', 'Aarau', 'Aandahl', 'Aani', 'Aaqbiye', 'Aalesund', 'Aalto', 'Aalborg', 'Aalst', 'Aachen', 'A-and-R']
[]

我做错了什么。

【问题讨论】:

  • 我不是在这里帮忙,但只知道__insert____get_all__非常糟糕的命名方法__&lt;name&gt;__ 方法是为 python 内置保留的,你不应该这样命名方法或属性。如果您想将其命名为“private”,您可以将其命名为 _&lt;name&gt;(技术上不是,但这是一种约定)
  • 同意,除了一个小点,它更像:_protected__private(按照惯例)
  • 您的测试输出是否理想?当你得到所有前缀为'A'的单词时,你只会得到以两个As开头的单词,比如AaronAalto。这是你想要的吗?
  • 问题出在print(trie.get_all_with_prefix(inputValue)) 函数中,它没有接受inputValue 并返回空列表[]。但是当我传递像print(trie.get_all_with_prefix("A")) 这样的字符串时,它工作得很好。我不知道这一行出了什么问题: print(trie.get_all_with_prefix(inputValue))

标签: python list tkinter


【解决方案1】:

你的问题是当你输入 A 然后按 space

inputValue = content_text.get("1.0", "end-1c")

返回'A ' 而不是'A'

这是因为 content_text.get() adds a new line character 在字符串的末尾。要同时忽略换行符和空格,请使用:

inputValue = content_text.get("1.0", "end-2c")

【讨论】:

  • 非常感谢@Josselin,你是救世主
  • 不客气,我使用pdb, the Python debugger 发现了问题。这是一个非常有用的工具! :)
猜你喜欢
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2013-10-21
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多