gpt4 book ai didi

python - 字符串拆分问题

转载 作者:太空狗 更新时间:2023-10-29 23:55:28 25 4
gpt4 key购买 nike

问题:通过作为列表传入的分隔符将字符串拆分为单词列表。

字符串:“洪水过后……所有的颜色都出来了。”

期望的输出:['After', 'the', 'flood', 'all', 'the', 'colors', 'came', 'out']

我已经编写了以下函数 - 请注意,我知道有更好的方法可以使用一些内置函数的 python 来拆分字符串,但为了学习,我认为我会继续这样做:

def split_string(source,splitlist):
result = []
for e in source:
if e in splitlist:
end = source.find(e)
result.append(source[0:end])
tmp = source[end+1:]
for f in tmp:
if f not in splitlist:
start = tmp.find(f)
break
source = tmp[start:]
return result

out = split_string("After the flood ... all the colors came out.", " .")

print out

['After', 'the', 'flood', 'all', 'the', 'colors', 'came out', '', '', '', '', '', '', '', '', '']

我不明白为什么“出来”不分成“来”和“出来”两个单独的词。就好像两个词之间的空白字符被忽略了一样。我认为输出的其余部分是垃圾,源于与“出来”问题相关的问题。

编辑:

我听从了@Ivc 的建议,得出了以下代码:

def split_string(source,splitlist):
result = []
lasti = -1
for i, e in enumerate(source):
if e in splitlist:
tmp = source[lasti+1:i]
if tmp not in splitlist:
result.append(tmp)
lasti = i
if e not in splitlist and i == len(source) - 1:
tmp = source[lasti+1:i+1]
result.append(tmp)
return result

out = split_string("This is a test-of the,string separation-code!"," ,!-")
print out
#>>> ['This', 'is', 'a', 'test', 'of', 'the', 'string', 'separation', 'code']

out = split_string("After the flood ... all the colors came out.", " .")
print out
#>>> ['After', 'the', 'flood', 'all', 'the', 'colors', 'came', 'out']

out = split_string("First Name,Last Name,Street Address,City,State,Zip Code",",")
print out
#>>>['First Name', 'Last Name', 'Street Address', 'City', 'State', 'Zip Code']

out = split_string(" After the flood ... all the colors came out...............", " ."
print out
#>>>['After', 'the', 'flood', 'all', 'the', 'colors', 'came', 'out']

最佳答案

您不需要内部循环调用。仅此就足够了:

def split_string(source,splitlist):
result = []
for e in source:
if e in splitlist:
end = source.find(e)
result.append(source[0:end])
source = source[end+1:]
return result

您可以通过在将 source[:end] 附加到列表之前检查它是否为空字符串来消除“垃圾”(即空字符串)。

关于python - 字符串拆分问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10809302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com