Python,按外观顺序输出字符串中找到的列表中的所有单词



该函数将我想要返回的单词列表(如果它们出现在字符串中(作为由" "分隔的字符串。但是,现在它们将按照传递给函数的列表中的外观顺序返回。如何修改我的函数,以便它们按字符串中的出现顺序返回?

我发现的唯一类似的帖子是这个返回第一个单词及其在python 2.x中的帖子: 抓取在字符串中找到的列表中的第一个单词。( 蟒蛇 (

def ifExiste(set):
count_tweet_adding = 0
tempvalue = []
value = ""
x=0
old_count = count_tweet_adding
for element in set:
if (word_tweet.find(element) >= 0):
tempvalue.append(element.strip())
count_tweet_adding +=1
value = tempvalue[0] 
if (old_count == count_tweet_adding):
value = "NaN"
while x < len(tempvalue)-1:
x += 1 
value = value + " " + tempvalue[x]
return value

编辑: 这是我是如何做到的:

我添加了一个循环来过滤字符串和我的单词列表中的单词,然后将这个过滤列表与"蛮力"方法逐个字母检查我的字符串。我还添加了一个替换 lign 来获取我从字符串中拾取的单词,这样如果它在我的字符串中出现两次,我可以捕获它两次。

def ifExiste(text, input_list):
count_tweet_adding = 0
tempvalue = []
value = ""
old_count = count_tweet_adding
filtered_input_list = []
for word in input_list:
if word in text:
filtered_input_list.append(word)
for length in range(len(text)):
for word in filtered_input_list:
if word in text[:length+1]:
tempvalue.append(word)
text = text[:length+1].replace(word,'')+text[length+2:]
count_tweet_adding +=1
tempvalue = map(str.strip, tempvalue)
value = " ".join(tempvalue)
if (old_count == count_tweet_adding):
value = "NaN"
return value

这是一个快速而肮脏(暴力(的解决方案。

假设您有一个要比较的以下字符串,因为您提到分隔符(或分隔符(是 "。

>>> s = "herearesomewordsinastringinsomeorder"

现在假设您有一个列表l,您要与s和文档进行比较的单词。

>>> l = ['string', 'the', 'in', 'appear', 'words', 'these', 'do']

然后,您可以初始化一个新列表newlist,以l中的单词以与它们在s中出现的顺序相同的顺序记录单词。

>>> newlist = []

然后,您可以编写以下类型的 for-each-in 循环:

>>> for length in range(len(s)):
...     for word in l:
...             if word in s[:length+1] and word not in newlist:
...                     newlist.append(word)

在评估时,会给你:

>>> newlist
['words', 'in', 'string']

按照它们在s中出现的顺序.

你可以用表达式来做到这一点!

def fn(s, input_list):
return list(x for x in s.split() if x in input_list)

这的工作原理是首先将字符串s成一个列表,然后迭代它,找到所有input_list

>>> fn("one two three", ["three", "two", "missing"])
['two', 'three']

对于小字符串来说,这应该是完全合理的

如果要创建新字符串,可以使用" ".join()"

>>> " ".join(fn("one two three", ["three", "two", "missing"]))
'two three

如果始终要返回新字符串,可以直接返回联接值,而不是创建新列表。

def fn(s, input_list):
return " ".join(x for x in s.split() if x in input_list)

最新更新