检查对象是否已经存在,如果存在则执行一些代码

Checking to see if a Object already exists and executing a bit of code if it does

这是在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 函数return一个“单词”对象列表,而不是:

        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 例如可能是“This is yes another Sentence” 这将是它得到的字符串的组合,但不等于它们中的任何一个。

搞清楚了,谢谢 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。

扩展了之前的评论:

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

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