2016-09-12 5 views
0

を使用して、キーワードやフレーズのリストが含まれている文を抽出私は、ファイルから文を抽出するために、次のコードを使用しているのpython

search_keywords=['mother','sing','song'] 
with open('text.txt', 'r') as in_file: 
    text = in_file.read() 
    sentences = text.split(".") 

for sentence in sentences: 
    if (all(map(lambda word: word in sentence, search_keywords))): 
     print sentence 

問題を(文は、検索キーワードの一部またはすべてを含める必要があります)上記のコードでは、検索キーワードの1つが文の単語と一致しない場合に、必要な文を印刷しないということです。検索キーワードの一部またはすべてを含む文章を出力するコードが必要です。コードがフレーズを検索して対応するセンテンスを抽出することができれば、それは素晴らしいことです。

+0

あなたは意味します'all()'ではなく 'any()'を使いますか? –

+0

search_keywordsが3であるとすると、コードはすべてのキーワードを含む文章を印刷しなければなりません。そうでなければ、2つの存在をチェックしなければなりません....そうでなければ1つのキーワード –

+1

回答を書いて編集しましたうまくいけばあなたの質問に完全に答えます –

答えて

2

各文にsearch_keyboardsの数を数えたいと思うようです。次のようにあなたはこれを行うことができます。

sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother".split(".") 
search_keywords=['mother','sing','song'] 

for sentence in sentences: 
    print("{} key words in sentence:".format(sum(1 for word in search_keywords if word in sentence))) 
    print(sentence + "\n") 

# Outputs: 
#2 key words in sentence: 
#My name is sing song 
# 
#1 key words in sentence: 
# I am a mother 
# 
#0 key words in sentence: 
# I am happy 
# 
#2 key words in sentence: 
# You sing like my mother 

それとも、唯一の最もマッチングsearch_keywordsを持っている文(複数可)したい場合、あなたは辞書を作ると最大値を見つけることができた:

dct = {} 
for sentence in sentences: 
    dct[sentence] = sum(1 for word in search_keywords if word in sentence) 

best_sentences = [key for key,value in dct.items() if value == max(dct.values())] 


print("\n".join(best_sentences)) 

# Outputs: 
#My name is sing song 
# You sing like my mother 
0

少なくとも1つのキーワードを含む文章を検索する必要があります。 all()の代わりにany()を使用できます。

編集:私が正しく理解していれば

sent_words = [] 
for sentence in sentences: 
    sent_words.append(set(sentence.split())) 
num_keywords = [len(sent & set(search_keywords)) for sent in sent_words] 

# Find only one sentence 
ind = num_keywords.index(max(num_keywords)) 
# Find all sentences with that number of keywords 
ind = [i for i, x in enumerate(num_keywords) if x == max(num_keywords)] 
+0

これは、検索キーワードを含むいくつかの文を印刷します。しかし、私が望むのは、ほとんどの検索キーワードが最良の答えである文章です。 –

+0

コードを編集しました。 – MaSdra

0

、あなたがany()代わりのall()を使用する必要があります。 あなたが最もキーワードが含まれている文を検索する場合。

if (any(map(lambda word: word in sentence, search_keywords))): 
    print sentence 
+0

このコードは、検索キーワードを含む複数の文章を出力します。しかし、私が望むのは、ほとんどの検索キーワードが最良の答えである文章です。 –

関連する問題