繁体   English   中英

我如何在Python中的关键搜索词之前和之后显示2个单词

[英]How I display 2 words before and after a key search word in Python

Python编程很新。 如何在关键搜索词之前和之后显示2个单词。 在下面的例子中,我正在寻找一个搜索词=列表

样品:

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

感谢您的帮助。

通过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

该解决方案基于Avinash Raj的第二个例子,其中包含以下修订:

  • 允许在搜索字的每一侧打印的字数可以改变
  • 使用列表理解来代替if里面for ,这可以被认为是更“Python化”,虽然我在这种情况下,我不知道,如果是更具可读性。

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]))

这是我能立即想到你的问题的解决方案:-)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM