Python 中的匹配行

发布于 2024-11-18 10:49:17 字数 735 浏览 2 评论 0原文

我需要匹配文本文件中的某些字符串并希望返回匹配行。比方说,我在 2D 数组中有一个字符串,如下所示:

[['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby'],
 ['My Cherie Amour (song)', 'Stevie Wonder'],
 ["Signed, Sealed, Delivered I'm Yours", 'Stevie Wonder]]

这样我就可以在文本文件中搜索该字符串,例如: ['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby' ]['', ''] ['', ''].... 在 file.txt 中,各行如下所示:

abcd Shoo-Be-Doo-Be-Doo-Da-Day skakk gkdka kkhhf Henry Cosby.
gfigka Stevie Wonder hfkhf hghhg fghh My Cherie Amour.
fhsgs hlghhg  Henry Cosby Shoo-Be-Doo-Be-Doo-Da-Day gkgkl.

然后我应该返回整行并标记匹配字符串。 对于一维数组,以下代码有效:

def search(word, sentences):
    return[i for i in sentences if word in i]

对于上面的二维数组,如何继续?

I need to match some string in a text file and want to get return the matching line. Let's say, I have string in 2D array as follows:

[['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby'],
 ['My Cherie Amour (song)', 'Stevie Wonder'],
 ["Signed, Sealed, Delivered I'm Yours", 'Stevie Wonder]]

So that I can search in a text file for the string e.g.: ['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby']['', ''] ['', ''].... In file.txt the lines look like this:

abcd Shoo-Be-Doo-Be-Doo-Da-Day skakk gkdka kkhhf Henry Cosby.
gfigka Stevie Wonder hfkhf hghhg fghh My Cherie Amour.
fhsgs hlghhg  Henry Cosby Shoo-Be-Doo-Be-Doo-Da-Day gkgkl.

then I should get return the whole line with marking the matches string.
For 1D array the following code works:

def search(word, sentences):
    return[i for i in sentences if word in i]

For the above 2D-array, how to proceed on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

维持三分热 2024-11-25 10:49:17

这个怎么样:

def search(sentences, words):
  return [s for s in sentences if all([w in s for w in words])]

How about this:

def search(sentences, words):
  return [s for s in sentences if all([w in s for w in words])]
沫尐诺 2024-11-25 10:49:17

这应该有效:

def search(patterns, sentences):
    for sentence in sentences:
        if any(all(p in sentence for p in pattern) for pattern in patterns):
            yield sentence

matched = list(search(['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby'],
                      sentences))

This should work:

def search(patterns, sentences):
    for sentence in sentences:
        if any(all(p in sentence for p in pattern) for pattern in patterns):
            yield sentence

matched = list(search(['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby'],
                      sentences))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文