0

テキストからリストを生成する関数を作成する必要があります。

text = '^to[by, from] all ^appearances[appearance]'

list = ['to all appearances', 'to all appearance', 'by all appearances', 
        'by all appearance', 'from all appearances', 'from all appearance']

つまり、角かっこ内の値は、^の直後にある前の単語を置き換えることになっています。以下に示すように、関数に5つの引数が必要です...

私のコード(動作しません)

def addSubstitution(buf, substitutions, val1='[', val2=']', dsym=',', start_p="^"):
    for i in range(1, len(buf), 2):
        buff = []
        buff.extend(buf)
        if re.search('''[^{2}]+[{0}][^{1}{0}]+?[{1}]'''.format(val1, val2, start_p,     buff[i]):
            substrs = re.split('['+val1+']'+'|'+'['+val2+']'+'|'+dsym, buff[i])
            for substr in substrs:
                if substr:
                    buff[i] = substr
                    addSubstitution(buff, substitutions, val1, val2, dsym, start_p)
        return
    substitutions.add(''.join(buf))
    pass

def getSubstitution(text, val1='[', val2=']', dsym=',', start_p="^"):
    pattern = '''[^{2}]+[{0}][^{1}{0}]+?[{1}]'''.format(val1, val2, start_p)
    texts = re.split(pattern,text)
    opttexts = re.findall(pattern,text)
    buff = []
    p = iter(texts)
    t = iter(opttexts)
    buf = []
    while True:
        try:
            buf.append(next(p))
            buf.append(next(t))
        except StopIteration:
            break
     substitutions = set()
     addSubstitution(buf, substitutions, val1, val2, dsym, start_p)
     substitutions = list(substitutions)
     substitutions.sort(key=len)
     return substitutions
4

1 に答える 1

1

1つのアプローチは次のとおりです(文字列操作コードをスキップしています):

text = '^to[by, from] all ^appearances[appearance]'

ステップ 1: 次textのようにトークン化します。

tokenizedText = ['^to[by, from]', 'all', '^appearances[appearance]']

ステップ 2: デカルト積が必要なすべての単語 (^ で始まる単語) のリストを準備します。

combinationList = []
for word in tokenizedText:
    if word[0] == '^': # split the words into a list, and add them to `combinationList`.

combinationList = [['to', 'by', 'from'], ['appearances', 'appearance']]

ステップ 3: 次を使用してデカルト積を実行しitertools.product(...)ます。

for substitution in itertools.product(*combinationList):
    counter = 0
    sentence = []
    for word in tokenizedInput:
        if word[0] == '^':
            sentence.append(substitution[counter])
            counter += 1
        else:
            sentence.append(word)
   print ' '.join(sentence)    # Or append this to a list if you want to return all substitutions.
于 2013-03-08T08:18:08.433 に答える