2

特定の文字列のドキュメントを検索し、各インスタンスのコンテキストを見つけられるようにしたいと考えています。たとえば、"Figure" のドキュメントを検索し、その文字列に続く X 文字を返します ("Figure-1 Super awesome figure. 次の文." から "-1 Super awesome figure" を返します)。

次のいずれかを印刷する方法を知っています:A)その文字列の各インスタンス

mystring = "Figure"
with open('./mytext.txt', 'r') as searchfile:
    for line in searchfile:
        if mystring in line:
            print(mystring)

しかし、それは何の助けにもなりません。または B) その文字列を含む各行

for line in open('./mytext.txt', "r"):
    if "Figure" in line:
        print(line) 

これは、行全体の前後のすべてのテキストを返しますが、これは私の目的にとっては面倒です。

「mystring」で行を分割し、分割後に X 文字を返すことはできますか? それとも、より良いアプローチがありますか?

4

3 に答える 3

0

次のようなことができます:

line = "Figure-1 Super awesome figure. next sentence."

search_line = line.split("Figure")

print search_line

# prints ['', '-1 Super awesome figure. next sentence.']

count = 0
for elem in search_line: 
    count += len(elem)

print count # how many chars after "Figure"
于 2013-11-13T00:34:25.087 に答える