2017-02-14 7 views
1

私はメソッドを持つ以下のクラスを持っている:私はそれを達成したいことは['regards', 'Regards']切断は

のような特定のトリガ・ワードの後に​​文の中で「ゴミ」のカットすることである

class Trigger(): 

    def getRidOfTrashPerSentence(self, line, stopwords): 
     countWord = 0 
     words = line.split() 
     for word in words: 
      if countWord == 0: 
       if word in stopwords: 
        sep = word 
        lineNew = line.split(sep, 1)[0] 
        countWord = countWord + 1 
        return(lineNew) 

    stopwords = ['regards', 'Regards'] 

    def getRidOfTrash(self, aTranscript): 
     result = [self.getRidOfTrashPerSentence(line, self.stopwords) for line in aTranscript] 
     return(result) 

01:私はこのような出力を探しています

aTranScript = [ "That's fine, regards Henk", "Allright great"] 

だから私はこのようなブロックを挿入するとき

aTranScript = [ "That's fine, regards", "Allright great"] 

は、しかし、私はこれを行うとき:

newFile = Trigger() 
newContent = newFile.getRidOfTrash(aTranScript) 

私だけ"That's fine"を取得します。

私は、文字列

+0

スプリット後にセパレータを追加するのはどうですか? これは似たような質問です - http://stackoverflow.com/questions/7866128/python-split-without-removing-the-delimiter – Vinay

+0

私はあなたがVinayを理解していません、あなたはこれについて詳述できますか? –

+0

あなたがこれを行うことができます - 'lineNew = line.split(9月、1)[0]' 'lineNew + = sep' – Vinay

答えて

2

の両方を得ることができますどのように、これは簡単な解決策である上の任意の考え:

yourString = 'Hello thats fine, regards Henk' 
yourString.split(', regards')[0] 

このコードは返されます:「こんにちはthatsの罰金」

をしたい場合は、最終的に「敬意」を結ぶことができます:

yourString.split( '、regards')[0] + '、regards'

+0

@EricDuminilあなたはrigth、変更されている 'ヘンク' の」について;) – Ika8

+0

場合あなたは特定の単語が見つからない場合、それを連結することができます.. – Ika8

+0

どのように複数のトリガーワードにそれを適応させるでしょうか? –

0

あなたがラインから単語をスキャンして、前の単語がストップワードであれば、それらを削除することができます。

class Trigger(): 

    stopwords = ['regards', 'Regards'] 

    def getRidOfTrashPerSentence(self, line): 
     words = line.split() 
     new_words = [words[0]] 
     for i in range(1, len(words)): 
      if not words[i-1] in self.stopwords: 
       new_words.append(words[i]) 
     return " ".join(new_words) # reconstruct line 

    def getRidOfTrash(self, aTranscript): 
     result = [self.getRidOfTrashPerSentence(line) for line in aTranscript] 
     return(result) 

aTranScript = [ "That's fine, regards Henk", "Allright great"] 
newFile = Trigger() 
newContent = newFile.getRidOfTrash(aTranScript) 
print(newContent) 
1

正規表現は、それが簡単に交換することができます。あなたがあなたのリストに'regards''Regards'を記述する必要はありませんので、ボーナスとして、それは大文字と小文字を区別しません:

import re 

stop_words = ['regards', 'cheers'] 

def remove_text_after_stopwords(text, stop_words): 
    pattern = "(%s).*$" % '|'.join(stop_words) 
    remove_trash = re.compile(pattern, re.IGNORECASE) 
    return re.sub(remove_trash, '\g<1>', text) 

print remove_text_after_stopwords("That's fine, regards, Henk", stop_words) 
# That's fine, regards 
print remove_text_after_stopwords("Good, cheers! Paul", stop_words) 
# Good, cheers 
print remove_text_after_stopwords("No stop word here", stop_words) 
# No stop word here 

あなたは文字列のリストを持っている場合、あなたはこの方法を適用するために、リストの内包表記を使用することができますすべての文字列に適用されます。