0

バイグラムとトライグラムのリストがあります:

string = 'do not be sad'

a_list: = ['do', 'not', 'do not', 'be', 'not be', 'do not be', 'sad', 'be sad', 'not be sad']

バイグラムとトリグラムを逆にする機能があるかどうか疑問に思っていましたa_listか?すべての文字列を結合して重複を削除できることはわかっていますが、それでは文の構造が失われます。a_list元の文字列に戻すことができるように、誰かがヒントを持っているかどうかを探しています。

望ましい出力は次のようになります。

b_list = ['do not be sad']
4

2 に答える 2

1

これを試して

string = 'do not be sad'
string = string.split()

a_list = ['do', 'not', 'do not', 'be', 'not be', 'do not be', 'sad', 'be sad', 'not be sad']

new = []

for a in string:
    for b in a_list:
        if a == b:
            new.append(b)

print([' '.join(new)])

出力

['do not be sad']

素敵なワンライナーにすることができます

print([' '.join([b for a in string for b in a_list if a == b])])

編集:ゾンドのコメントに応えて、回答を編集することにしました。さらに、この問題は非常に興味深いことがわかりました

a_list = ['do', 'not', 'do not', 'be', 'not be', 'do not be', 'sad', 'be sad', 'not be sad']
a_list = ['This', 'is', 'This is', 'my', 'is my', 'This is my', 'car', 'my car', 'is my car']
a_list = ['i', 'am', 'i am', 'a' , 'am a', 'i am a', 'boy', 'a boy', 'am a boy']

largest = max(a_list, key=len) # get the longest sub word in the list

# loop through and if all words of a sublist don't exist in the largest sub word then join them together
for elem in a_list:
    sp = elem.split()
    if all(i not in largest for i in sp):
        if a_list.index(elem) < a_list.index(largest):
            print([elem + ' ' + largest])
        else:
            print([largest + ' ' + elem])

また、ソリューションをテストするためにいくつかのテストケースを作成しましたが、それらはすべて合格しました

于 2016-02-18T12:26:12.023 に答える