用于在文本中查找单词并返回文本和计数的Python脚本

时间:2013-09-15 12:52:32

标签: python text-files

我有一个包含小文本的文本文件。我需要一个python中的脚本,它允许我查找一个特定的单词(例如“food”),它将打印前面的5个字符,并且还会打印单词(“food”)的出现总数。结束。

示例:

“你不需要携带很多食物。在包装你的食物之前,你应该通过愿望清单。所有的食物都将在抵达后进行检查。”

期望的结果:

“t of”,“your”,“All”

第3

任何帮助都非常感激。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

(.{5})表示捕获任意(.)五个({5})个字符,后跟字符串"%s" % word,后者嵌入与变量{{1}相关联的字符串像这样进入文本:word - > "%s" % "food"

"food"