首页 > 解决方案 > Python,按外观顺序从字符串中找到的列表中输出所有单词

问题描述

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

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

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

标签: pythonpython-3.x

解决方案


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

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)

推荐阅读