【问题标题】:search a specific item of a list in a string python在字符串 python 中搜索列表的特定项目
【发布时间】:2019-02-08 21:01:37
【问题描述】:

我有两个字符串:

 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 有 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”

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

【问题讨论】:

  • 在您的示例中,“快速”中的“快速”如何?
  • “Quickly”里面包含“Quick”这个词
  • 你应该在你的例子中改变它。因为你有Next word is "quick", since quick is found inside of "Quickly", quick would be the next word in string C
  • 我编辑了,现在更好了吗?

标签: python string list for-loop python-3.6


【解决方案1】:

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

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

【讨论】:

  • elem 是做什么的?
  • elem 是一个变量,它保存正在迭代的列表/字符串的当前元素。
猜你喜欢
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 2011-08-19
  • 2013-01-20
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多