您好,我正在编写一个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.
答案 0 :(得分:2)
我们可以在代表行尾的字符上分割文本,然后在这些行中循环并打印出包含我们关键字的行。
要在多个字符上分割文本,例如可以使用! ? .
标记行尾,我们可以使用正则表达式:
import re
keyword = "data"
line_end_chars = "!", "?", "."
example = "Welcome to SOF! This website securely stores data for the user?"
regexPattern = '|'.join(map(re.escape, line_end_chars))
line_list = re.split(regexPattern, example)
# line_list looks like this:
# ['Welcome to SOF', ' This website securely stores data for the user', '']
# Now we just need to see which lines have our keyword
for line in line_list:
if keyword in line:
print(line)
但是请记住:
if keyword in line:
与以下序列匹配 字符,不一定是一个完整的单词-例如, “ datamine”是对的。如果您只想匹配整个单词,则应该 使用正则表达式: source explanation with example
答案 1 :(得分:2)
我的方法类似于Alberto Poljak,但更加明确。
这样做的动机是认识到不需要拆分单词-Python的in
运算符会很高兴在句子中找到单词。句子的拆分是必要的。不幸的是,句子可以以.
,?
或!
结尾,而Python的split
函数不允许多个分隔符。因此,我们必须变得有点复杂并使用re
。
re
要求我们在每个定界符和其中的 escape 之间放置一个|
,因为.
和?
都有特殊含义默认情况下。 Alberto的解决方案本身使用re
来完成所有这一切,这绝对是可行的方法。但是,如果您不熟悉re
,我的硬编码版本可能会更清晰。
我进行的另一项添加是将每个句子的结尾定界符放回到它所属的句子上。为此,我将定界符包装在()
中,该定界符将它们捕获到输出中。然后,我使用zip
将它们重新放在它们来自的句子上。 0::2
和1::2
切片将采用每个偶数索引(句子),并将它们与每个奇数索引(定界符)连接起来。取消注释print
语句以查看正在发生的事情。
import re
lines = "Welcome to SOF! This website securely stores data for the user. Another sentence."
keyword = "data"
sentences = re.split('(\.|!|\?)', lines)
sentences_terminated = [a + b for a,b in zip(sentences[0::2], sentences[1::2])]
# print(sentences_terminated)
for sentence in sentences_terminated:
if keyword in sentence:
print(sentence)
break
输出:
This website securely stores data for the user.
答案 2 :(得分:1)
此解决方案使用一个相当简单的正则表达式,以便在句子中找到您的关键字,该关键字前后可能有也可能没有,最后一个句点字符也是如此。它适用于空格,并且仅执行re.search()
。
import re
text_file = open("file.txt", "r")
text = text_file.read()
keyword = 'data'
match = re.search("\s?(\w+\s)*" + keyword + "\s?(\w+\s?)*.", text)
print(match.group().strip())
答案 3 :(得分:0)
另一种解决方案:
def check_for_stop_punctuation(token):
stop_punctuation = ['.', '?', '!']
for i in range(len(stop_punctuation)):
if token.find(stop_punctuation[i]) > -1:
return True
return False
text_file = open("file.txt", "r")
lines = []
lines = text_file.read().split()
keyword = 'data'
sentence = []
stop_punctuation = ['.', '?', '!']
i = 0
while i < len(lines):
token = lines[i]
sentence.append(token)
if token == keyword:
found_stop_punctuation = check_for_stop_punctuation(token)
while not found_stop_punctuation:
i += 1
token = lines[i]
sentence.append(token)
found_stop_punctuation = check_for_stop_punctuation(token)
print(sentence)
sentence = []
elif check_for_stop_punctuation(token):
sentence = []
i += 1