2015-02-05 178 views
0

Python编程很新颖。我如何在关键字搜索词前后显示2个单词。在下面的例子,我在寻找一个搜索词=列表如何在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 

感谢在这你的帮助。

+0

是否打印整行或仅打印关键字前后的文字? –

+0

只想打印前后的单词。如果我可以灵活地将这些单词从2更改为5等,那将是非常好的。 – Murali

+0

为什么期望的输出不包含“PythonLearn”?在我的例子中, –

回答

0

解决方案上阿维纳什·拉吉与这些修正案第二个例子中该解决方案是基于:

  • 允许在搜索词的每一面打印单词的数量以改变
  • 使用列表理解而不是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])) 
+0

非常感谢。这真是太棒了!我非常感谢你的帮助。所有都是很好的解决方 – Murali

+0

是否可以在第3个字段(文本字段)中与numwords = 2一起执行相同的查找词?我想保留两个领域没有改变参考。完整性。我输入文件: 12088 | CITA | {你好非常好的清单,更好地保持这些 12089 | CITA |这是列表很棒的主题保持它 我想要的输出文件: 12088 | CITA |非常好的列表,更好到 12089 | CITA |列表主题保留它 – Murali

+0

您的意思是你想输出整个输入行直到搜索词,然后是接下来的两个单词?只需用'0'替换最后一行中的'max(x-numwords,0)'。或者我误解了你之后的事情? – nekomatic

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 
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 
相关问题