0

ランダムなタイトルとランダムな説明を生成できる Python ライブラリはありますか。

ランダム タイトル: 5 語未満の、文法的に正しい (ただしランダムな) 英文。ランダムな説明: 20 語未満の、文法的に正しい (ただしランダムな) 英文。

タイトルと説明フィールドを持つ製品をテストしています。「タイトル 1」「説明 1」ではなく、ランダムなタイトルとランダムな説明で複数のオブジェクトを作成したいと考えています。

4

1 に答える 1

5

かなり単純な解決策として、次のような正規表現の一致を見つけるだけです[A-Z][a-z'\-]+[, ]([a-zA-Z'\-]+[;,]? ){15,25}[a-zA-Z'\-]+[.?!](大文字の単語の後に 15 ~ 25 の単語が続き (カンマまたはセミコロンが続く可能性があります)、その後に最後の単語と句読点が続きます)文章。タイトルのような短いフレーズを取得するには、約 5 単語の任意のシーケンスに一致させることができます (おそらく句読点は必要ありません)。 ([a-zA-Z'\-]+ ){4,6}


Python を使用したマルコフ連鎖による疑似ランダム テキストの生成から:

これを実現するには、マルコフ連鎖を使用できます。そのためには、次の手順を実行する必要があります (リンクしたページから)。

  1. 次のトランジションを選択するコーパスとして機能するテキストを用意します。
  2. テキストの 2 つの連続する単語から始めます。最後の 2 つの単語は現在の状態を構成します。
  3. 次の単語を生成するのがマルコフ遷移です。次の単語を生成するには、コーパスを調べて、指定された 2 つの単語の後に存在する単語を見つけます。それらのいずれかをランダムに選択します。
  4. 必要なサイズのテキストが生成されるまで、2 を繰り返します。

これを達成するために彼らが提供するコード:

import random

class Markov(object):

    def __init__(self, open_file):
        self.cache = {}
        self.open_file = open_file
        self.words = self.file_to_words()
        self.word_size = len(self.words)
        self.database()


    def file_to_words(self):
        self.open_file.seek(0)
        data = self.open_file.read()
        words = data.split()
        return words


    def triples(self):
        """ Generates triples from the given data string. So if our string were
                "What a lovely day", we'd generate (What, a, lovely) and then
                (a, lovely, day).
        """

        if len(self.words) < 3:
            return

        for i in range(len(self.words) - 2):
            yield (self.words[i], self.words[i+1], self.words[i+2])

    def database(self):
        for w1, w2, w3 in self.triples():
            key = (w1, w2)
            if key in self.cache:
                self.cache[key].append(w3)
            else:
                self.cache[key] = [w3]

    def generate_markov_text(self, size=25):
        seed = random.randint(0, self.word_size-3)
        seed_word, next_word = self.words[seed], self.words[seed+1]
        w1, w2 = seed_word, next_word
        gen_words = []
        for i in xrange(size):
            gen_words.append(w1)
            w1, w2 = w2, random.choice(self.cache[(w1, w2)])
        gen_words.append(w2)
        return ' '.join(gen_words)

このコードを使用して、次の例のように、jeeves.txt を選択したシード テキストに置き換えます (長いほど良い)。

In [1]: file_ = open('/home/shabda/jeeves.txt')

In [2]: import markovgen

In [3]: markov = markovgen.Markov(file_)

In [4]: markov.generate_markov_text()
Out[4]: 'Can you put a few years of your twin-brother Alfred,
who was apt to rally round a bit. I should strongly advocate
the blue with milk' 

In[1] から In[3] までの後は、必要にmarkov.generate_markov_text()応じて 5 語と 20 語のシーケンスを生成する適切な引数を指定して呼び出す必要があります。

于 2013-11-09T06:52:17.320 に答える