Python 中的匹配行
我需要匹配文本文件中的某些字符串并希望返回匹配行。比方说,我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个怎么样:
How about this:
这应该有效:
This should work: