在单独的行上显示“word”结果,并打印包含单词的句子的第一个单词(Python)

2024-06-25 23:43:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我对这个问题有意见,有人能帮我吗?你知道吗

编写一个程序读入书本.txt,询问用户密码是什么,然后打印出包含该单词的所有句子的第一个单词,忽略大小写。包括所有包含子字符串的句子,即使它是单词的一部分。

那个书本.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

Tags: andthetoin程序txt单词句子
1条回答
网友
1楼 · 发布于 2024-06-25 23:43:15
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
>>> 

相关问题 更多 >