在python的字符串列表中找到确切的单词列表? [英] find the exact list of words in list of strings in python?

查看:56
本文介绍了在python的字符串列表中找到确切的单词列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串列表:

grids = ['north', 'eaSt', 'West','noRtheast', 'soUth']
links = ['north-northeast', 'north-south']

我想检查链接中有哪些grids.所以我为此写了一个程序:

I want to check that what grids are there in the links. So I wrote a program for this:

import re

grids = ['north', 'eaSt', 'West','noRtheast', 'soUth']
links = ['north-northeast', 'north-south']

for search in grids:
    for text in links:
        result = re.findall('\\b' + search + '\\b', text, flags=re.IGNORECASE)
        print(result)

输出:

['north']
['north']
[]
[]
[]
[]
['northeast']
[]
[]
['south']

我几乎得到了输出,但不明白为什么我会在输出中得到这些空白,所以我能得到更简单、更干净的替代方案吗?

I almost got the output but don't understand that why am I getting those blanks in the output, so can I get the simpler and clean alternative for this one, please?

推荐答案

可能不需要为此使用正则表达式.只需检查字符串是否存在.

Probably don't need regex for this. Just check if the string exists.

grids = ['north', 'eaSt', 'West','noRtheast', 'soUth']
links = ['north-northeast', 'north-south']
for l in links:
    print(f'{l} contains {[x for x in grids if x.lower() in l.lower().split("-")]}')

输出

north-northeast contains ['north', 'noRtheast']
north-south contains ['north', 'soUth']

这篇关于在python的字符串列表中找到确切的单词列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆