-2

私はPythonでこのようなことをしようとしています。

私の単語リストが次のとおりであるとします。

is, are, was, the, he, she, fox, jumped

そして私のテキストはのようなものHe was walking down the road.です。

を返す関数を作成したい

['He', ' ', 'was', ' ', 'w','a','l','k','i','n','g', ' ', 'd','o','w','n',' ', 'the', 'r','o','a','d','.']

つまり、すべての文字が要素であるリストを返しますが、単語リスト内の単語は 1 つの要素と見なされます。

誰か、この関数の作成を手伝ってください

4

2 に答える 2

3
t = ['is', 'are', 'was', 'the', 'he', 'she', 'fox', 'jumped']
s = "He was walking down the road."
new = []
for word in phrase.split(): 
    if word.lower() in filters:
            new.append(word)
    else:
            new.extend(word)
    new.append(' ')

print new[:-1] # We slice the last element because it is ' '.

版画:

['He', ' ', 'was', ' ', 'w', 'a', 'l', 'k', 'i', 'n', 'g', ' ', 'd', 'o', 'w', 'n', ' ', 'the', ' ', 'r', 'o', 'a', 'd', '.']

関数として:

def filter_down(phrase, filters):
    new = []
    for word in phrase.split(): 
        if word.lower() in filters:
                new.append(word)
        else:
                new.extend(list(word)) # list(word) is ['w', 'a', 'l', 'k', 'i', 'n', 'g']
        new.append(' ')
    return new
于 2013-07-07T04:59:23.850 に答える
1

私の最初の Python コードです。うまくいくことを願っています。

array = ["is", "are", "was", "the", "he", "she", "fox", "jumped"]
sentence = "He was walking down the road"
words = sentence.split(" ");
newarray = [];
for word in words:
    if word.lower() in array:
         newarray.append(word)
    for i in range(0, len(word), 1):
         newarray.append(word[i:i+1])
    newarray.append(" ")

for word in newarray:
     print word
于 2013-07-07T05:02:10.260 に答える