繁体   English   中英

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

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

我有两个字符串:

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

两者都已在每个空间转换为列表。 我想创建一个 for 循环,将列表 A 中的每个单词一个接一个,如果找到,则在字符串 B 中搜索它,然后将该单词添加到新字符串中。 一旦找到这个词,它就会删除第二个字符串中该词的整个第一次出现。 它区分大小写,“the”与“The”不同。我对如何在字符串中搜索特定单词然后将其删除感到困惑。

所以首先它会从列表 A 中取出单词“The”并在字符串 B 中搜索它,因为发现新字符串将由单词“The”组成。 下一个单词是quick,字符串B has quick,单词Quickly 包含quick,所以quick 将被添加到新字符串中。

我到目前为止的代码:

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):

如果我将列表 A 中的每个单词搜索到字符串 B,我会得到“The quick brown fox did jump a”

注意:每个单词都区分大小写,如果操作正确,则不应出现重复单词。

您可以尝试的一件事是,当您将两个字符串转换为列表时,在两个字符串的每个单词中放置一个空格字符作为前缀和后缀,然后在需要最终输出时将其删除:

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)

输出:

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