-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','.']

它将返回一个列表,其中每个字母都是一个元素,但单词列表中的单词被视为一个元素。

有人,请帮我创建这个功能

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 回答