【问题标题】:Search through a list of strings for a word that has a variable character在字符串列表中搜索具有可变字符的单词
【发布时间】:2019-07-19 19:31:54
【问题描述】:

基本上,我从插入单词“brand”开始,将单词中的单个字符替换为下划线,然后尝试查找与其余字符匹配的所有单词。例如:

"b_and" 将返回:"band"、"brand"、"bland" .... 等等。

我开始使用 re.sub 替换字符中的下划线。但我真的不知道下一步该去哪里。我只想要这个下划线不同的单词,要么没有下划线,要么用字母替换。就像如果“under”这个词贯穿整个列表,我不希望它返回“understood”或“thunder”,只是一个字符差异。任何想法都会很棒!

我尝试先用字母表中的每个字母替换字符,然后再检查该单词是否在字典中,但这花了很长时间,我真的想知道是否有更快的方法

from itertools import chain

dictionary=open("Scrabble.txt").read().split('\n')

import re,string

#after replacing the word with "_", we find words in the dictionary that match the pattern
    new=[]
    for letter in string.ascii_lowercase:
        underscore=re.sub('_', letter, word)
        if underscore in dictionary:
            new.append(underscore)
    if new == []:
        pass
    else:
        return new

【问题讨论】:

    标签: python list search


    【解决方案1】:

    IIUC 应该这样做。我在函数之外执行此操作,因此您有一个工作示例,但在函数内部执行此操作很简单。

    string = 'band brand bland cat dand bant bramd branding blandisher'
    word='brand'
    new=[]
    for n,letter in enumerate(word):
        pattern=word[:n]+'\w?'+word[n+1:]
        new.extend(re.findall(pattern,string))
    new=list(set(new))
    

    输出:

    ['bland', 'brand', 'bramd', 'band']
    

    解释:

    我们正在使用regex 来做您正在寻找的事情。在这种情况下,在每次迭代中,我们都会从“品牌”中取出一个字母,并让算法寻找任何匹配的单词。所以它会寻找:

    _rand、b_and、br_nd、bra_d、bran_

    对于“b_and”的情况,模式是b\w?and,意思是:找到一个带有b的单词,然后任何字符可能出现也可能不出现,然后是'and'。

    然后它将所有匹配的单词添加到列表中。

    最后我用list(set(new))删除重复项

    编辑:忘记添加string vairable。

    【讨论】:

      【解决方案2】:

      这是 Juan C 的答案的一个版本,它有点 Pythonic

      import re
      
      dictionary = open("Scrabble.txt").read().split('\n')
      pattern = "b_and" # change to what you need
      pattern = pattern.replace('_', '.?')
      pattern += '\\b'
      
      matching_words = [word for word in dictionary if re.match(pattern, word)]
      

      编辑:根据您的评论修复正则表达式,快速解释:

      pattern = "b_and"
      pattern = pattern.replace('_', '.?') # pattern is now b.?and, .? matches any one character (or none at all)
      pattern += '\\b' # \b prevents matching with words like "bandit" or words longer than "b_and"
      

      【讨论】:

      • 这很好,但我怎样才能只获得单个字符不同的单词的结果?我得到了 'blandished'、'blandisher'、'blandishers' 的结果,我只想要单个字符差异
      • 我添加了 '\b' 到我的,我相信这可以解决您的问题
      猜你喜欢
      • 2014-03-25
      • 2011-12-27
      • 2019-01-05
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      相关资源
      最近更新 更多