简体   繁体   English

在字符串python中搜索列表的特定项目

[英]search a specific item of a list in a string python

I have two strings:我有两个字符串:

 a = "The quick brown fox did jump over a log"
 b = "The brown rabbit quickly did outjump the fox"

both of which have been converted into lists at each space.两者都已在每个空间转换为列表。 I want to make a for loop that takes each word one by one in list A and searches it in string B if it is found then the word gets added to a new string.我想创建一个 for 循环,将列表 A 中的每个单词一个接一个,如果找到,则在字符串 B 中搜索它,然后将该单词添加到新字符串中。 Once the word is found, it deletes the entire first occurrence of the word in the second string.一旦找到这个词,它就会删除第二个字符串中该词的整个第一次出现。 It is case sensitive, "the" is not the same as "The".I am confused about how to search for a specific word in a string and then delete it.它区分大小写,“the”与“The”不同。我对如何在字符串中搜索特定单词然后将其删除感到困惑。

So first it would take the word from list A "The" and search for it in string B, since it is found the new string will consist of the word "The".所以首先它会从列表 A 中取出单词“The”并在字符串 B 中搜索它,因为发现新字符串将由单词“The”组成。 Next word is quick, String B has quickly, the word Quickly contains quick, so then quick would be added to the new string.下一个单词是quick,字符串B has quick,单词Quickly 包含quick,所以quick 将被添加到新字符串中。

The code I have so far:我到目前为止的代码:

a = "The quick brown fox did jump over a log"
b = "The brown rabbit quickly did outjump the fox"

import re

aa = re.sub("[^\w]", " ",  a).split()
bb = re.sub("[^\w]", " ",  b).split()
for aa[0] in range(b):

If I were to search every word in List A to string B, I would get "The quick brown fox did jump a "如果我将列表 A 中的每个单词搜索到字符串 B,我会得到“The quick brown fox did jump a”

Note: each word is case sensitive and if done right there should be no repetition of words.注意:每个单词都区分大小写,如果操作正确,则不应出现重复单词。

One thing you can try is to place a space character both as prefix and suffix in each word of both strings when you convert them to lists and then remove them when you want the final output:您可以尝试的一件事是,当您将两个字符串转换为列表时,在两个字符串的每个单词中放置一个空格字符作为前缀和后缀,然后在需要最终输出时将其删除:

a = "The quick brown fox did jump over a log"
b = "The brown rabbit quickly did outjump the fox"

# Convert to list with prefix and suffix.
listA = [' ' + elem + ' ' for elem in a.split()]
listB = [' ' + elem + ' ' for elem in b.split()]

# Loop to check for each word in listA if it's in listB.
c = []
for elem in listA:
    if elem in listB:
        c.append(elem[1:-1]) # Append element without prefix and suffix.
        listB.remove(elem)

b = " ".join([elem[1:-1] for elem in listB]) # Remove prefix and suffix.
c = " ".join(c)

print("New string:", c)
print("New b:", b)

Output:输出:

New string: The brown fox did
New b: rabbit quickly outjump the

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM