【问题标题】:Using a tree in python to get values在python中使用树来获取值
【发布时间】:2014-02-07 22:32:54
【问题描述】:

所以我正在尝试使用 Python 创建一棵树,以便能够尝试读取文件中具有重复数量的文本文件,并尝试从这些值中创建一棵树并返回前 3 个句子值(下面有更详细的解释)。

首先,我在 wikipedia 上搜索了如何创建树,并且还看到了 stackoverflow 上的先前示例,例如:This one。和This one。但是,就代码而言,我只能做到这一点:

import fileinput

setPhrasesTree = 0


class Branch():
    def __init__(self, value):
        self.left = None
        self.right = None
        self.value = value

class Tree():
    def __init__(self):
        self.root = None
        self.found = False

    #lessThan function needed to compare strings
    def lessThan(self, a, b):    
        if len(a) < len(b):
            loopCount = len(a)
        else:
            loopCount = len(b)        
        for pos in range(0, loopCount):
            if a[pos] > b[pos]:
                return False        
        return True

    def insert(self, value):
        self.root = self.insertAtBranch(self.root, value)

    def exists(self, value):
        #set the class variable found to False to assume it is not there      
        self.found = False
        self.findAtBranch(self.root, value)
        return self.found

    #Used to fine a value in a tree
    def findAtBranch(self, branch, value):        
        if branch == None:
            pass
        else:
            if branch.value == value:
                self.found = True                
            else:
                self.findAtBranch(branch.left, value)
                self.findAtBranch(branch.right, value)        

    def insertAtBranch(self, branch, value):
        if branch == None:
            return Branch(value)
        else:
            if self.lessThan(branch.value, value):
                branch.right = self.insertAtBranch(branch.right, value)            
            else:
                branch.left = self.insertAtBranch(branch.left, value)
            return branch

def loadTree(filename, treeType):

    if treeType == setPhrasesTree:
        for sentence in fileinput.input("setPhrases.txt"):
            print(sentence)
            setPhrases.insert(sentence[:-1])


def findSentenceType(sentence):

    if sentence.exists(sentence):
        return setPhrasesTree

这是文本文件的样子。请记住,它是故意这样布置的,而不是旁边的数量值(文件名 = setPhrases.txt):

Hi my name is Dave.
Thank-You.
What is your name?
I have done all my homework.
What time is dinner?
What is your name?
Thank-You.
Hi my name is Dave.
What is your name?
I have done all my homework.
What is your name?
Can you bring me a drink Please?
Can you bring me a drink Please?
What is your name?
Hi my name is Dave.
What is your name?
Can you bring me a drink Please?

这是我试图让我的代码做的事情。我需要它来识别文件中的第一句话是起始节点。然后它需要统计所有其他相同的句子,并为该句子添加一个值,然后使用树来执行此操作。 (我最初是用另一种方式做到这一点的,但是我需要使用一棵树来计算并做所有其他事情)这就是我的意思:

然后我希望能够返回频率最高的前 3 个Phrases。所以在这种情况下,系统将返回句子(按此顺序):

What is your name?
Hi my name is Dave.
Can you bring me a drink please?

非常感谢任何帮助。也感谢您的宝贵时间。

【问题讨论】:

  • 我理解正确吗,您只是想计算文件中每行出现的频率吗?你几乎不需要一棵树。
  • @pentadecagon 是的,正如我之前提到的,我已经能够做到这一点。但是,我必须使用树来执行此操作,而且我不知道下一步该做什么。
  • 需要树吗?所以这是练习吗?可以肯定的是,因为你知道,这个问题可以通过使用字典而不是树来更有效地解决,只需要大约 20 行代码。如果你真的想要一棵树,那么为了让这棵树有用,它可能应该是某种self-balancing tree,这里最受欢迎的是red-black tree。这需要您自己完成很多工作。
  • @pentadecagon 你能告诉我如何按照你的方式去做,但也要实现一种方法,以便用户可以选择一个选项,它会在 txt 文件中的计数中添加 +1 的分数?
  • 你说的文本文件中的tally是什么意思?这会是什么样子?

标签: algorithm python-3.x tree return-value


【解决方案1】:

给你,一个使用字典的实现。这是你想要的吗?

import collections
def count_lines():
    d = collections.defaultdict(int)
    for line in open( "phrases.txt" ):
        d[ line.strip() ] += 1

    # we use the negative count as sort key, so the biggest ends up first
    a = sorted( d.items(), key=lambda x : -x[1] )
    for n, u in enumerate( a[:3] ):
        print( u[0], "# count=", u[1] )

count_lines()        

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多