[英]How can I simplify this function?
有什么方法可以簡化此功能? 具體來說,我想用更少的縮進行來重寫它。
# split string (first argument) at location of separators (second argument, should be a string)
def split_string(text, separators):
text = ' ' + text + ' '
words = []
word = ""
for char in text:
if char not in separators:
word += char
else:
if word:
words.append(word)
word = ""
if not words:
words.append(text)
return words
您的代碼似乎產生了
>>> split_string("foo.,.bar", ".,")
[' foo']
但是你的評論說
split_string("foo.,.bar", ".,") will return ["foo", "bar"]
假設注釋是什么意思,那么我將使用itertools.groupby
(我討厭使用正則表達式):
from itertools import groupby
def splitter(text, separators):
grouped = groupby(text, lambda c: c in separators)
return [''.join(g) for k,g in grouped if not k]
這使
>>> splitter("foo.,.bar", ".,")
['foo', 'bar']
groupby
返回按術語的某些函數(在本例中為lambda c: c in separators
分組的連續術語上的迭代器。
您應該使用split()
方法。 取自官方文件:
str.split([sep [,maxsplit]])
使用sep作為分隔符字符串,返回字符串中單詞的列表。 如果指定了maxsplit,則最多完成maxsplit個分割(因此,列表最多包含maxsplit + 1個元素)。 如果未指定maxsplit或-1,則分割數沒有限制(進行所有可能的分割)。
如果給定sep,則不將連續的定界符分組在一起,而是將其視為定界空字符串(例如'1,,2'.split(',')返回['1','','2'])。 sep參數可以包含多個字符(例如,'1 <> 2 <> 3'.split('<>')返回['1','2','3'])。 使用指定的分隔符分割空字符串將返回['']。
如果未指定sep或為None,則將應用不同的拆分算法:連續的空白行將被視為單個分隔符,並且如果字符串的開頭或結尾處有空格,則結果在開頭或結尾將不包含空字符串。 因此,使用None分隔符拆分空字符串或僅包含空格的字符串將返回[]。
例如,'1 2 3'.split()返回['1','2','3'],'1 2 3'.split(None,1)返回['1','2 3' ]。
你可以做:
myString = "Some-text-here"
splitWords = myString.split("-")
上面的代碼將返回一個列表,其中包含單詞。 我使用“-”作為分隔符,您可以分配任何喜歡的分隔符。 默認為“空格”定界符,如下所示:
myString = "Some text here"
splitWords = myString.split()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.