【问题标题】:Checking to see if a Object already exists and executing a bit of code if it does检查对象是否已经存在,如果存在则执行一些代码
【发布时间】:2021-01-27 10:43:55
【问题描述】:

这是在 Python 中。

我想在我的计算器上用大约 75 行代码编写一个简单的马尔可夫链。我能够导入的唯一模块是“随机”和“数学”。

这是我制作的一个快速副本,应该可以在 python 终端中工作,它应该可以工作。
这是我的计算器拥有它的唯一方法。

from random import *

class word:
    def __init__(self,word,words):
        self.word=word
        self.words=words.split()

    def addWord(self,word):
        self.words.append(word)

# "x" is an empty list, otherwise contains all previous word-objects
# "s" is the string to use for training
def train(x,s):
    s=s.split()
    if len(x)==0:
        x=[]
    for i in range(len(s)-1):
        if s[i]==s[-1]:
            return x
    w=word(s[i],s[i+1])
    ind=0
    # ///
    # This is the problem area
    for wr in x:
        ind+=1
        if wr in x:
            wr.addWord(s[i+1])
        elif wr not in x:
            x.append(w)
    # ///
    return x

def chain(start, x):
    for i in range(10):
        for w in x:
            if w.word==start[-1]:
                start.append(choice(w.words))
    return start

我希望 train 函数返回一个“单词”对象列表,而不是:

        if wr in x:
            wr.addWord(s[i+1])
        elif wr not in x:
            x.append(w)

似乎永远不会被执行,我会继续研究这个,因为肯定有解决方案。

TL:DR;我如何检查一个对象是否在对象列表中,如果是,则向该对象添加一些内容,如果它没有将该对象添加到列表中?

如果您需要更多信息,请随时询问。

如果您想对其进行测试,请将其附加到代码中:

x=[]
x=train(x, "This is a String")
x=train(x, "And this is yet another Sentence")
y=chain(x, "This")
print(y)

其中 x 是最后所有单词的字典 y 是生成的句子。

我希望使用给定的单词和上下文生成一个未经训练的句子。 上下文和来自它训练的句子的单词。

y 例如可能是“这是另一个句子” 这将是它得到的字符串的组合,但不等于它们中的任何一个。

【问题讨论】:

  • 您好,您的代码中有错误。过度检查逻辑?你是编程/python 新手吗?
  • 您所展示的正是如何做到这一点。你没有描述的是你期望它如何工作。您的 word 对象在实现时将简单地测试 identity,但我想,您还有其他一些语义?
  • 好吧,我本身不是新手,我已经编写 python 代码 2 年了,但这只是我计算器的一个快速而肮脏的副本,我会调查并修复它。
  • 很简单的方法:使用set 而不是list 并始终进行添加。
  • @guidot 这实际上是一个非常好的技巧,我没想到。

标签: python markov-chains


【解决方案1】:

扩展了之前的评论:

很简单的方法:使用 set 而不是 list 并始终进行添加。

如果我正确理解了对我的评论的回复,使用 set 作为值的 defaultdict 可能是要走的路,关键是单词的最后一个字母。 (我不得不猜测,因为示例代码中没有chain的调用者。)

【讨论】:

  • 正如我在问题中所说,所有方法都需要手动调用,因为我在只执行“从主导入 *”的计算器上运行它,您也可以在 CMD 中执行此操作。关键不是单词的最后一个字母,关键是单词本身。这是一个例子:字符串(作为一个句子)被拆分:[“This”,“Is”,“a”,“Sentence”]来自“This Is a Sentence”,所以“This”例如会在字典中构建这个: "This": Word("This", "Is") 理论上我也可以完全放弃 Word 类。 “这个”:[“是”,“其他词”]
【解决方案2】:

想通了,谢谢guidot。

字典解决了我所有的问题,因为它不允许重复,我可以简单地通过单词本身搜索单词,非常适合我。

words={
        "if": Word("if","they")
    }
try:
    words[word].addword(wordAfter)
except:
    words[word]=Word(word,wordAfter)

这应该做我想做的,对吧?

只需要重写我的代码。

// 完成 现在可以了!

完整代码如下:

from random import *


class Word:
    def __init__(self, word, words):
        self.word = word
        self.words = words.split()

    def addword(self, newword):
        self.words.append(newword)


def train(x, s):
    s = s.casefold().split()
    if len(x) == 0:
        x = {}
    for i in range(len(s) - 1):
        if s[i] == s[-1]:
            return x
        try:
            x[s[i]].addword(s[i + 1])
        except:
            x[s[i]] = Word(s[i], s[i + 1])
    return x


def chain(x, start):
    for i in range(100):
        try:
            w = x[start[-1]]
            start.append(choice(w.words))
        except:
            continue
    return start


x = []

trainingStrings = [
    "is this another training string",
    "this is another string of training",
    "training of string is important",
    "the training of this string is important",
    "important is what this string is",
    "is this string important or can is it training",
    "it is a string for training a string"
     "important this is this important is",
     "this is is important this is",
]

for i in trainingStrings:
    x = train(x, i)

for i in range(10):
    y = chain(x, ["this"])
    print(" ".join(y))

特别感谢 guidot。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2019-03-28
    相关资源
    最近更新 更多