擅长:python、mysql、java
<p>你把两个问题混成了一个。第一个问题是:如何从字符串中删除非字母数字字符?有几种方法可以实现,但正则表达式替换是一种不错的方法。在</p>
<pre><code>import re
def removeWhitespace( s ):
return re.sub( '\s', '', s )
</code></pre>
<p>问题的第二部分是关于如何在关键字中循环,直到文本行被消耗。你可以这样写:</p>
^{pr2}$
<p>大多数pythonists都会看到这一点并看到重构的机会。这段代码试图实现的模式是在称为<code>zip</code>的函数式编程中实现的。奇怪的是,在本例中,您对关键字的重复字符进行了稍微不规范的处理,这也有一个等价的函数,itertools模块中的<a href="http://docs.python.org/library/itertools.html#itertools.cycle" rel="nofollow">cycle</a>函数。在</p>
<pre><code>from itertools import cycle, islice, izip
def characterZip( keyword, textline ):
textline = removeWhitespace(textline)
textlen = len(textline)
it = islice( izip(cycle(keyword), textline), textlen )
return [ '%s%s' % val for val in it ]
</code></pre>