python - 查找字符串列表中的所有子字符串并创建一个新的匹配子字符串列表。在Python中

标签 python string loops substring

我有一个子字符串列表和一个字符串列表。我想在字符串列表中找到所有匹配的子字符串。当在字符串中找到子字符串时,我想创建一个新的字符串列表,其中包含每个字符串中找到的所有子字符串匹配项。

例如,假设我有这些:

substrings = ["word","test"]

strings = ["word string one", "string two test", "word and test", "no matches in this string"]

我创建了以下内容来将子字符串与字符串进行匹配:

for s in strings:
for k in substrings:
    if k in s:
        print(k)

这给出以下输出:

word
test
word
test 

我还尝试了以下方法:

matches = [x for string in strings for x in string.split() if x in substrings]
print (matches)

输出:

['word', 'test', 'word', 'test']

这些结果都不是我所追求的。由于“word”和“test”都出现在第三个字符串中,我希望得到类似于以下输出之一的内容:

word
test
word, test 

['word', 'test', 'word test']

最佳答案

您的代码没有给您想要的结果,因为您没有将多个匹配项保留在自己的列表中。

实现您正在寻找的内容的最简单方法是在循环内保留另一个列表以包含与当前字符串匹配的子字符串。

substrings = ["word","test"]

strings = ["word string one",
           "string two test",
           "word and test",
           "no matches in this string"]

result = []    

for string in strings:
    matches = []
    for substring in substrings:
        if substring in string:
            matches.append(substring)
    if matches:
        result.append(matches)

这应该给你

[['word'], ['test'], ['word', 'test']]

如果您想实际以问题中所述的格式打印这些内容,只需更改

result.append(matches)

print(' '.join(matches))

这会给你:

word
test
word test

关于python - 查找字符串列表中的所有子字符串并创建一个新的匹配子字符串列表。在Python中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44095595/

相关文章:

Javascript 使用 RegExp 替换字符串模式?

c - scanf() 在 for 循环中不能正常工作

python - 循环更新pyplot 3d散点图,网格线重叠点

python - 计数 'x' 是否出现在一列中并且 'y' 出现在另一列中

python - 如何考虑元素的位置来一一比较numpy数组元素?

python - 传递给 scipy.optimize.curve_fit 的函数需要满足哪些特定要求才能运行?

java - 使用java删除另一个双引号内的双引号

python - 如何使用 smtplib 和 MIMEText 发送电子邮件?

c# - 使用 string.format(...) 输出 '{' 或 '}'

java - 我怎样才能让这个方 block 从墙上弹起来?