簡體   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