0

我有一个包含小文本的文本文件。我需要一个python脚本,它可以让我查找一个特定的单词(例如“food”),它将打印前5个字符,并且还将打印单词(“food”)在结束。

例子:

“你不需要带很多食物。在打包你的食物之前,你应该检查一下愿望清单。所有的食物都会在抵达时进行检查。”

期望的结果:

“t of”、“你的”、“全部”

3

非常感谢任何帮助。

4

2 回答 2

1

如果有帮助,试试这个。

>>> s = "You won't need to bring a lot of food with you. Before packing your food you should run through the wish list. All food will be inspected upon arrival."
>>> t = "food"
>>> s.split(t)
["You won't need to bring a lot of ", ' with you. Before packing your ', ' you should run through the wish list. All ', ' will be inspected upon arrival.']
>>> result = [part[-5:] for part in s.split(t)[:-1]]
>>> print result
['t of ', 'your ', ' All ']
>>> print len(result)
3
于 2013-09-15T13:27:26.790 回答
1

您可以使用正则表达式来捕获前面的五个字符。

(.{5})表示捕获任何 ( .) 五个 ( {5}) 字符,其后跟"%s" % word将与变量关联的字符串嵌入word到文本中的字符串,如下所示:"%s" % "food"-> "food"

>>> import re
>>> word = 'food'
>>> m = re.findall(r'(.{5})%s'%word,t)
>>> print m,len(m)
['t of ', 'your ', ' All '] 3
于 2013-09-15T13:31:07.753 回答