带isli的python itertools

2024-10-02 12:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我还在学习python,我有下面的代码,但它不起作用:

from itertools import *

startword = ["start",]
stopword = ["stop",]
text = "this is a text that starts with some test stuff and then after that it stop right here!"

for i in islice(text.split(" "), startword, stopword):
    print i

我试着在开始和结束之间打印单词,而不知道中间有多少个单词。 从这个错误看来,我需要一个整数作为islice的启动和停止参数。以下是错误“ValueError: Indices for islice() must be None or an integer: 0 <= x <= maxing.” 还有我能用的其他itertool吗?!在

谢谢


Tags: 代码textfromimportforthat错误this
2条回答

您需要计算“开始”和“停止”的索引,然后提供 两个整数值,不是字符串:

for i in islice(text.split(" "), startword_index, stopword_index):
    print i

在这个特定的例子中,islice是一个糟糕的选择;您在内存中有所有的数据,在一个实现的序列中,所以{}只是在浪费时间迭代前导值。有很多更好的方法来处理这个问题,或者使用index来找到start和{}索引并做一个真正的切片,或者更聪明地通过分割start/end分隔的部分并只分割该部分来提取单词来减少工作量。例如:

text = "this is a text that starts with some test stuff and then after that it stop right here!"

_, text = text.split('start', 1)  # Remove start and stuff before it
text, _ = text.rsplit('stop', 1)  # Remove stop and stuff after it

for word in text.split():  # Split what remains on whitespace
    print word

请注意,这仍然不是很正确(您的有界区域以“starts”开头,而不是“start”,因此您以一个前导的“word”结束“s”),但是使用适当的边界和通配符切换到{}可以用任何适合您的场景的方式来解决这个问题。在

相关问题 更多 >

    热门问题