首页 > 解决方案 > 检查对象是否已经存在,如果存在则执行一些代码

问题描述

这是在 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:博士;我如何检查一个对象是否在对象列表中,如果是,则向该对象添加一些内容,如果它没有将该对象添加到列表中?

如果您需要更多信息,您可以自由提问。

如果要测试它,请将其附加到代码中:

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”,它是它得到的字符串的组合,但不等于其中任何一个。

标签: pythonmarkov-chains

解决方案


想通了,谢谢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。


推荐阅读