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

编辑:这是我的方法:


我添加了一个循环来过滤字符串和我的单词列表中的单词,然后将此过滤后的列表与“蛮力”方法一起使用来逐个字母地检查我的字符串。我还添加了一个替换符号,以将我从字符串中拾取的单词取出,因此,如果它在字符串中出现两次,则可以捕获两次。


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


慕田峪4524236
浏览 468回答 2
2回答

忽然笑

这是一个快速而肮脏的(暴力)解决方案。假定您具有以下要比较的字符串,因为您提到的分隔符(或定界符)为“”。>>> s = "herearesomewordsinastringinsomeorder"现在假设您有一个list l,要与之进行比较的单词s并进行记录。>>> l = ['string', 'the', 'in', 'appear', 'words', 'these', 'do']然后,您可以初始化一个新列表,newlist以l按照出现的顺序记录单词s。>>> newlist = []然后,您可以编写一个for-each-in循环:>>> for length in range(len(s)):...&nbsp; &nbsp; &nbsp;for word in l:...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if word in s[:length+1] and word not in newlist:...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;newlist.append(word)经评估,这将为您提供:>>> newlist['words', 'in', 'string']按照他们出现的顺序s。

吃鸡游戏

您也许可以使用表达式来做到这一点!def fn(s, input_list):&nbsp; &nbsp; 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):&nbsp; &nbsp; return " ".join(x for x in s.split() if x in input_list)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python