問題:文字列をリストとして渡された区切り文字で単語のリストに分割します。文字列の分割問題
文字列:"After the flood ... all the colors came 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])
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', '', '', '', '', '', '', '', '', '']
二つの別々の単語として「来て」と「アウト」に分割されていない「出てきた」なぜ私が把握することはできません。 2つの単語の間の空白文字が無視されているかのようなものです。私はアウトプットの残りの部分が、「出てきた」問題に関連する問題に由来するジャンクだと思う。
EDIT:
私は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']
素晴らしいソリューションをありがとうございました。私はこのビルドを行っています。なぜなら、あらかじめビルドされた関数を使用するのではなく、ロジックを学ばなければならないからです。明らかに、私が商用コードを書くなら、私は車輪を再発明しないだろうが、学習目的のために私はこの答えに行くだろう。皆さんのお手伝いをありがとうございます。 – codingknob