繁体   English   中英

在 python 的字符串列表中找到确切的单词列表?

[英]find the exact list of words in list of strings in python?

我有两个字符串列表:

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

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

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)

OUTPUT:

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

我几乎得到了 output 但不明白为什么我会在 output 中得到这些空白,所以我可以为这个获得更简单和干净的替代品吗?

可能不需要正则表达式。 只需检查字符串是否存在。

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("-")]}')

Output

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

当常规 Exp 找不到任何内容时,您的代码打印结果也会出现。 if检查数组是否为空,您可以添加一些

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)
        if len(result):
            print(result)

我不知道图书馆“re”,但我想我可以像这样解决你的问题:

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

for search in grids:
    for text in links:
        if search.lower() in text.lower():
            print('find '+search+' in '+text+' !') 

string 上的 method.lower() 会将所有基于大小写的字符小写,如果字符串search在字符串text中,则运算符in将返回 true。

好吧我有误会,你可以在比较之前拆分链条:

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

for search in grids:
    for text in links:
        for text_split in text.split('-'):
            if search.lower() == text_split.lower():
                print('find '+search+' in '+text+' !')

OUTPUT:

find north in north-northeast !
find north in north-south !
find noRtheast in north-northeast !
find soUth in north-south !

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM