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

问题描述

这是用 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 可能例如是“这是另一个句子” 这将是它得到的字符串的组合,但不等于它们中的任何一个

解决方法

想通了,谢谢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 并始终进行添加。

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