过滤单词列表(Python)

时间:2013-07-07 04:43:16

标签: python function text python-2.7

我正在尝试用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','.']

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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