查找字符串中“单词”的位置并打印字符串中“单词”前后的 N 个字符

时间:2021-01-03 19:10:08

标签: python string

假设我有一个字符串存储在变量 text 中:

text = "Lorem ipsum dolor sit example amet"

如何让 Python 在字符串中查找单词 "example" 并将其与前后 3 个字符一起打印?例如,对于上面的字符串,它应该打印:

"it example am"

4 个答案:

答案 0 :(得分:3)

像这样使用 re.findall

import re
text = "Lorem ipsum dolor sit example amet"
substr = re.findall(r'.{0,3}example.{0,3}', text)
print(substr[0])
# it example am

我使用的是 .{0,3}(任何字符重复 0 到 3 次,包括在内)而不是更简单的 .{3}...(两者都意味着任何字符完全重复 em> 3 次)以避免失败并显示错误消息 'IndexError: list index out of range',对于距离字符串开头或结尾少于 3 个字符的单词(例如 Loremamet)。

答案 1 :(得分:0)

text = "Lorem ipsum dolor sit example amet"

word_list = text.split()

for i in range(len(word_list)):
    if word_list[i] == 'example' and i != 0 and i != len(word_list)-1:
        print (word_list[i-1][-2:]+" "+word_list[i]+" "+word_list[i+1][0:2])
    elif word_list[i] == 'example' and i != 0:
        print (word_list[i-1][-2:]+" "+word_list[i])
    elif word_list[i] == 'example' and i != len(word_list)-1:
        print (word_list[i]+" "+world_list[i+1][0:2])

你从你的字符串中创建一个列表,space split()。

您检查列表中的每个单词,条件是您的请求对于第一个和最后一个单词是不可能的。

然后打印前面的最后两个字符,空格,您要查找的单词,空格,两个第一个字符或后面的字符。

输出:

it example am

答案 2 :(得分:0)

您可以使用 str.find() 来获取搜索词的索引,然后使用常规字符串切片来获取单词和两边的所有内容。

ex = 'example'
index = text.find(ex)
if index != -1:
    start = max(0, index - 3)
    finish = index + len(ex) + 3
    print(text[start:finish])

答案 3 :(得分:0)

您可以使用str.index找到子字符串的位置,然后使用字符串切片获取子字符串为:

text = "Lorem ipsum dolor sit example amet"
search = "example"

try:
    k = text.index(search)  # Raises `ValueError` exception if 
                            # `search` text not present in `text`
    my_substring = text[max(k-3, 0): k+len(search)+3]
                       # ^ To handle if `k-3` is less then 0
    print("Desired result: {}".format(my_substring))
except ValueError:
    print("'{}' is not present in '{}'".format(search, text))