cod*_*nob 6 python string split
问题:通过作为列表传入的分隔符将字符串拆分为单词列表.
串: "After the flood ... all the colors came out."
期望的输出: ['After', 'the', 'flood', 'all', 'the', 'colors', 'came', 'out']
我写了以下函数 - 注意我知道有更好的方法来使用函数内置的一些pythons来分割字符串但是为了学习我想我会这样做:
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', '', '', '', '', '', '', '', '', '']
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚为什么"出来"不会分成"来"和"出"两个单独的词.就好像两个单词之间的空白字符被忽略一样.我认为输出的其余部分是垃圾,源于与"出来"问题相关的问题.
编辑:
我按照@ 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']
Run Code Online (Sandbox Code Playgroud)
你似乎在期待:
source = tmp[start:]
Run Code Online (Sandbox Code Playgroud)
修改source外部 for 循环正在迭代的 。它不会 - 该循环将继续遍历您给它的字符串,而不是现在使用该名称的任何对象。这可能意味着你所扮演的角色可能不在剩下的内容中source。
不要尝试这样做,而是以这种方式跟踪字符串中的当前索引:
for i, e in enumerate(source):
...
Run Code Online (Sandbox Code Playgroud)
并且您要附加的内容将始终是source[lasti+1:i],并且您只需要跟踪即可lasti。
| 归档时间: |
|
| 查看次数: |
1488 次 |
| 最近记录: |