teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

3

追記

2019/09/24 14:24

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -18,4 +18,22 @@
18
18
  - 空白で分割して、単語を調べる?
19
19
  - 正規表現の単語境界を活用する?
20
20
 
21
- 解法は自由です。
21
+ 解法は自由です。
22
+ 後者についてはKojiDoiさんの回答に詳しいので、私は前者を書いてみます。
23
+ ```Python
24
+ >>>
25
+ >>> textlist = ["I saw a red apple", "I saw an apple", "I saw a reddish apple"] # お借りしました
26
+ >>> colors = ['red', 'blue', 'yellow',]
27
+ >>>
28
+ >>> for text in textlist:
29
+ ... words = text.lower().split()
30
+ ... if any(word in colors for word in words):
31
+ ... print('colors')
32
+ ... else:
33
+ ... print('not colors')
34
+ ...
35
+ colors
36
+ not colors
37
+ not colors
38
+
39
+ ```

2

追記

2019/09/24 14:24

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -11,4 +11,11 @@
11
11
  >>> import re
12
12
  >>> bool(re.search(r'red|blue|yellow', text))
13
13
  True
14
- ```
14
+ ```
15
+
16
+ ---
17
+ ただ、例えば redact とか predict も引っかかるのが問題です。
18
+ - 空白で分割して、単語を調べる?
19
+ - 正規表現の単語境界を活用する?
20
+
21
+ 解法は自由です。

1

追記

2019/09/24 12:49

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -3,4 +3,12 @@
3
3
  >>> colors = ['red', 'blue', 'yellow',]
4
4
  >>> any(color in text for color in colors)
5
5
  True
6
+ ```
7
+
8
+ 正規表現を使う方法もありますが、個人的には好みではありません。
9
+ 他の方法で充分記述できるのに、正規表現を持ち出すのが大げさに思えるからです。
10
+ ```Python
11
+ >>> import re
12
+ >>> bool(re.search(r'red|blue|yellow', text))
13
+ True
6
14
  ```