筛选单词列表(Python)
我正试图用Python做类似的事情 假设我的单词列表是:筛选单词列表(Python),python,function,text,python-2.7,Python,Function,Text,Python 2.7,我正试图用Python做类似的事情 假设我的单词列表是: is, are, was, the, he, she, fox, jumped 我的文字就像他在路上走一样。 我想创建一个函数,它将返回 ['He', ' ', 'was', ' ', 'w','a','l','k','i','n','g', ' ', 'd','o','w','n',' ', 'the', 'r','o','a','d','.'] 它将返回一个列表,其中每个字母都是一个元素,但单词列表中的单词被视为一个元素 有人,请
is, are, was, the, he, she, fox, jumped
我的文字就像他在路上走一样。
我想创建一个函数,它将返回
['He', ' ', 'was', ' ', 'w','a','l','k','i','n','g', ' ', 'd','o','w','n',' ', 'the', 'r','o','a','d','.']
它将返回一个列表,其中每个字母都是一个元素,但单词列表中的单词被视为一个元素
有人,请帮我创建这个函数
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
我的第一个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
你已经试过了吗?:)
list
调用可以省略:new.extend(word)
+1另一种方法:new.extend([word]如果word.lower()在filters-else-word中)
@FMc确实是一种可能性,但也许当前的解决方案更整洁?不过这很好:)当传递的文本是'walking'
但筛选器仅包含['walk']
时,我该怎么做才能将类似['walk'、'I'、'n'、'g']
的内容获取到函数中。请help@AgnishomChattopadhyay好问题;不知道!我试过一些东西,但这可能需要一个单独的问题。