查找文件中的所有字符串位置

时间:2015-02-25 13:04:36

标签: python

如果我想在文件中找到字符串的位置,我可以做到

f = open('file.txt', 'r')
lines = f.read()
posn = lines.find('string')

如果字符串在文件中多次出现并且我想找到它出现的所有位置怎么办?我有一个字符串列表,所以现在我的代码是

for string in list:
    f = open('file.txt', 'r')
    lines = f.read()
    posn = lines.find(string)

我的代码不完整,只找到列表中每个字符串的第一个位置

3 个答案:

答案 0 :(得分:3)

您可以使用以下

import re

a = open("file", "r")
g = a.read()
ma = re.finditer('test', g)
for t in ma:
    print t.start(), t.end()

可能的输出

  

8 12

     

16 20


例如:

g='hahahatesthahatesthahahatest'
ma=re.finditer('test',g)
for t in ma:
    print t.start(), t.end()

输出

  

6 10

     

14 18

     

24 28


print g[t.start():t.end()]按预期为您提供test

答案 1 :(得分:2)

您可以使用enumerate

>>> s='this is a string'
>>> def find_pos(s,sub):
...     return [i for i,j in enumerate(s) if j==sub]
... 

>>> find_pos(s,'s')
[3, 6, 10]

答案 2 :(得分:1)

这将返回文件中存在模式的位置。使用re.finditer

import re
with open('your.file') as f:
    text = f.read()
    positions = [m.span() for m in re.finditer('pattern', text)]
相关问题