Pythonを勉強している初心者です。
以下のコードで、text file内の英文を読み取って、statement(命題)として成立する文かそうじゃないかを分別するプログラムを練習で作っているのですが、分別する際のキーワードを並べた2行目のlistが21行目のelif構文内でうまく機能していないようです。
どうして動かないのか、どうすれば正しく動作するか、もしよろしければ教えて下さい。
使ったtext file の内容
Strawberries are fruit.
Do you like grape jelly?
The Church is true.
She sings well.
2 + 2 = 5
how are you doing
Go.
School is located in Japan
コード内容
from sys import argv
qWord = ["what","where","how","why","who","when","he","she","it","they"]
if len (argv) == 1:
print ("Type argument/filename.")
else:
filename = argv[1]
try:
with open(filename) as file:
contents = file.read()
except IOError:
print("No File Found")
else:
file = open(filename)
#process to open the file
for line in file:
line = line.rstrip()
if line[-1] == "?":
print(line+" NOT A STATEMENT")
elif " " not in line:
print(line+" NOT A STATEMENT")
elif line in qWord:
print(line+" NOT A STATEMENT")
else:
print(line+" STATEMENT")
コマンドライン内で本来の趣旨に則って動作した場合の反応
Strawberries are fruit. STATEMENT
Do you like grape jelly? NOT A STATEMENT
The Church is true. STATEMENT
She sings well. NOT A STATEMENT
2 + 2 = 5 STATEMENT
how are you doing NOT A STATEMENT
Go. NOT A STATEMENT
School is located in Japan STATEMENT
実際の反応
Strawberries are fruit. STATEMENT
Do you like grape jelly? NOT A STATEMENT
The Church is true. STATEMENT
She sings well. STATEMENT
2 + 2 = 5 STATEMENT
how are you doing STATEMENT
Go. NOT A STATEMENT
School is located in Japan STATEMENT
elif line in qWord:
の部分は、例えばelif any([word.lower() in qWord for word in line.split(' ')]):
の様になるでしょう(単純にスペースで分割しているだけなので不完全かもしれません)。any(word in line for word in qWord):
という形にしてプログラム走らせたところ無事動作しました!ありがとうございます!