我还在学习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吗?!在
谢谢
您需要计算“开始”和“停止”的索引,然后提供 两个整数值,不是字符串:
在这个特定的例子中,}只是在浪费时间迭代前导值。有很多更好的方法来处理这个问题,或者使用}索引并做一个真正的切片,或者更聪明地通过分割
islice
是一个糟糕的选择;您在内存中有所有的数据,在一个实现的序列中,所以{index
来找到start
和{start/end
分隔的部分并只分割该部分来提取单词来减少工作量。例如:请注意,这仍然不是很正确(您的有界区域以“starts”开头,而不是“start”,因此您以一个前导的“word”结束“s”),但是使用适当的边界和通配符切换到{}可以用任何适合您的场景的方式来解决这个问题。在
相关问题 更多 >
编程相关推荐