Python编程很新。如何在关键搜索词之前和之后显示2个单词。在下面的例子中,我正在寻找一个搜索word = lists
样品:
Line 1: List of the keyboard shortcuts for Word 2000
Line 2: Sequences: strings, lists, and tuples - PythonLearn
期望的结果(列表仅在第2行中找到的单词)
Line 2: Sequences: strings, lists, and tuples
感谢您的帮助。
答案 0 :(得分:2)
通过re.findall
功能。
>>> s = """List of the keyboard shortcuts for Word 2000
Sequences: strings, lists, and tuples - PythonLearn"""
>>> re.findall(r'\S+ \S+ \S*\blists\S* \S+ \S+', s)
['Sequences: strings, lists, and tuples']
没有正则表达式。
>>> s = """List of the keyboard shortcuts for Word 2000
Sequences: strings, lists, and tuples - PythonLearn"""
>>> for i in s.split('\n'):
z = i.split()
for x,y in enumerate(z):
if 'lists' in y:
print(z[x-2]+' '+z[x-1]+' '+z[x]+' '+z[x+1]+' '+z[x+2])
Sequences: strings, lists, and tuples
答案 1 :(得分:0)
这是我能立即想到你的问题的解决方案: - )
def get_word_list(line, keyword, length, splitter):
word_list = line.split(keyword)
if len(word_list) == 1:
return []
search_result = []
temp_result = ""
index = 0
while index < len(word_list):
result = word_list[index].strip().split(splitter, length-1)[-1]
result += " " + keyword
if index+1 > len(word_list):
search_result.append(result.strip())
break
right_string = word_list[index+1].lstrip(" ").split(splitter, length+1)[:length]
print word_list[index+1].lstrip(), right_string
result += " " + " ".join(right_string)
search_result.append(result.strip())
index += 2
return search_result
def search(file, keyword, length=2, splitter= " "):
search_results = []
with open(file, "r") as fo:
for line in fo:
line = line.strip()
search_results += get_word_list(line, keyword, length, splitter)
for result in search_results:
print "Result:", result
答案 2 :(得分:0)
此解决方案基于Avinash Raj的第二个例子,其中包含以下修订:
if
中使用列表推导而不是for
,这可能被认为更“Pythonic”,但在这种情况下我不确定它是否更具可读性。
s = """List of the keyboard shortcuts for Word 2000
Sequences: strings, lists and tuples - PythonLearn"""
findword = 'lists'
numwords = 2
for i in s.split('\n'):
z = i.split(' ')
for x in [x for (x, y) in enumerate(z) if findword in y]:
print(' '.join(z[max(x-numwords,0):x+numwords+1]))