显示 字n#39;单独行上的结果并打印包含单词(Python)的句子的第一个单词

时间:2014-08-31 05:10:05

标签: python

我遇到了这个问题的麻烦,有人可以帮帮我吗?

编写一个程序,在book.txt中读取,询问用户密码是什么,并打印出包含该单词的所有句子的第一个单词,忽略大小写。包括包含子字符串的所有句子,即使它构成单词的一部分。

book.txt文件每行有一个句子,如下所示:

The room was dark and dreary.
Beware what lies beneath.
She could barely make out the back wall.
Treasure was piled in the nearest corner, in the dark shadows.
Is this safe, she thought to herself, accidentally stubbing her toe on the dark carpet.
Mister Lieth said it would be cold.
Suddenly, a gust of wind rushed through the door from behind her.
In the wind, the candle struggled, plunging the room into semidarkness.
The thought of the already darkened room having still less light did not appeal to her.
Shivering, she closed the door, wishing she had brought a scarf.
Well and good, she had to focus before it was dark outside.
Black and grey shadows were all she had to believe in.

你的程序应该像这样工作:

Password: dark
the
treasure
is
in
the
well

1 个答案:

答案 0 :(得分:0)

def find_all(password, File_Path):
    password = password.lower()
    with open (File_Path, 'r') as o:
        for line in o:
            if password in line.lower():
                print line[:line.find(' ')]

您可以使用in

>>> find_all("dark", File_Path)
The
Treasure
Is
In
The
Well
>>> 


>>> find_all("lie", File_Path)
Beware
Mister
Black
>>>