E.g。我有文字:
"约翰起床了。约翰去了电影院。约翰洗了手。"
现在我想找到第一个" John"并做一些事情,然后我想去下一个" John"并做一些事情,所以我需要使用像findNext()
这样的东西来考虑实际位置,所以它不会从头开始,而是从实际位置找到。
答案 0 :(得分:2)
find-Method有一个start
- 参数:
text = "John got up. John went to the cinema. John washed his hand."
pos = -1
while True:
pos = text.find('John', pos + 1)
if pos == -1:
break
do_something
答案 1 :(得分:0)
如果要解析html / xml文档,请尝试使用网站上的beautiful soup安装说明。然后你可以做类似的事情,
soup = BeautifulSoup(text_in_string)
list = soup.findAll('id')
for each_id in list:
#do something
答案 2 :(得分:0)
好像你想要打印<id>
>>> s = '''<text>ala
<id>1
<text>david
<id>2
<text>john
<id>3
<text>gregory
<id>4
<text>dominic
<id>5
<text>david
<id>2'''
>>> re.findall(r'(?<=<id>)\d+', s)
['1', '2', '3', '4', '5', '2']
答案 3 :(得分:0)
在大多数情况下,丹尼尔写的是什么。但作为一个发电机:
def nextIndex(string: str, text: str, start: int=0):
while True:
try:
start = text.index(string, start)
yield start
start += 1
except ValueError:
raise StopIteration
text = "John got up. John went to the cinema. John washed his hand."
for i in nextIndex('John', text):
print(i)
答案 4 :(得分:-1)
我不确定我是否理解你的内容,但根据你的帖子,也许,它可能是这样的:
x = 'John'
y = ['got up','went to the cinema', 'washed hands']
for i in y:
print (x + ' ' + i)
这是输出:
John got up
John went to the cinema
John washed hands