[英]Python search text file, print characters following a string
我希望能夠在文檔中搜索給定的字符串並找到每個實例的上下文。 例如,在文檔中搜索“ Figure”,然后在該字符串后返回X個字符(從“ Figure-1 Super awesome Figure。next句話”中返回“ -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個字符嗎? 還是有一個更好的方法?
我會這樣做:
WANTED = 20 #or however many characters you want after 'Figure'
with open('mytext.txt') as searchfile:
for line in searchfile:
left,sep,right = line.partition('Figure')
if sep: # True iff 'Figure' in line
print(right[:WANTED])
請參閱: str.partition
您可以執行以下操作:
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"
import re
X = len("-1 Super awesome figure")
regex = re.compile("Figure.{%d}" % X)
for line in open("mytext.txt"):
for m in regex.findall(line):
print m
您可能需要澄清“返回該字符串后的X個字符”的含義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.