【问题标题】:find the exact list of words in list of strings in python?在python的字符串列表中找到确切的单词列表?
【发布时间】:2021-03-05 14:13:51
【问题描述】:

我有两个字符串列表:

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

我想检查gridslinks 中的内容。所以我为此写了一个程序:

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']

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

【问题讨论】:

    标签: python string python-re


    【解决方案1】:

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

    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']
    

    【讨论】:

    • 嘿,谢谢,伙计,这是一个非常干净的方法。
    【解决方案2】:

    当常规 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)
    

    【讨论】:

    • 是的,这可能是这个逻辑。谢谢
    【解决方案3】:

    我不知道图书馆“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+' !') 
    

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

    【讨论】:

    • 好吧,这种方法的唯一问题是它还会从“链接”中打印“东”,而实际上并不存在。这个方法我试过了。
    【解决方案4】:

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

    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+' !')

    输出:

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

    【讨论】:

      猜你喜欢
      • 2017-09-07
      • 2017-01-28
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多