【发布时间】:2019-04-06 20:58:46
【问题描述】:
您好,我正在编写一个 Python 程序,它读取给定的 .txt 文件并查找关键字。在这个程序中,一旦我找到了我的关键字(例如'data'),我想打印出与该词相关联的整个句子。
我已读入我的输入文件并使用split() 方法去除空格、制表符和换行符,并将所有单词放入一个数组中。
这是我到目前为止的代码。
text_file = open("file.txt", "r")
lines = []
lines = text_file.read().split()
keyword = 'data'
for token in lines:
if token == keyword:
//I have found my keyword, what methods can I use to
//print out the words before and after the keyword
//I have a feeling I want to use '.' as a marker for sentences
print(sentence) //prints the entire sentence
file.txt如下
Welcome to SOF! This website securely stores data for the user.
想要的输出:
This website securely stores data for the user.
【问题讨论】:
-
如果您使用
enumerate存储/循环索引并获取上一个和下一个索引,则可以。但更大的问题是先将 sentences 分开 -
如果token在一个句子中出现两次,是否应该打印多次?
-
@MelvinYellow 是的,保证可以在文本文件中找到该词
-
@Jean-FrançoisFabre 感谢枚举方法!这使得迭代更容易,至于分隔句子,我将使用句点 ('.') 作为标记。我只需要弄清楚如何检测数组中的句点,因为它附加到一个单词。
-
例如使用
word.endswith(".")。或正则表达式来检测标点符号