【问题标题】:More accurate alternative to findline?findline 的更准确的替代方案?
【发布时间】:2012-03-11 21:30:10
【问题描述】:

我有一个列表 (words.txt),我需要一种比 findline 更准确的搜索方法。

我当前的函数(显示在底部)使用findline 来搜索列表。问题是:findline 不是返回完全匹配,而是返回包含整个单词的第一个字符串,而不管它后面是否有更好的匹配。

示例: 我输入 'BEES' 并且 findline 返回 'BAUBEES' 因为它是第一个包含子字符串 ('BEES') 的字符串。当然,这完全破坏了功能。

我需要的是一个函数或(最好)一个内置的方法,该方法看起来 按字母顺序 完全匹配。所以如果'BEES'在列表中(我向你保证它是),我希望它返回'BEES'。或者,如果 'BAUBEES' 和 'BEESWAX' 是列表中唯一的子字符串匹配项,那么理想的函数将返回 'BEESWAX' 如果仅仅是因为 'BEES' 中的第二个字母是 'E' 而不是 'A' (如在 ' BAUBEES')。

def iswholeword(word):
    openfile = open('/media/Gianson/Python Programs/words.txt','r')
    linz = openfile.readlines()[:]
    openfile.close()
    hit = findline(word,linz)[:]
    print 'hit', hit
    if len(hit)-1  == len(word):
        return True
    else:
        return False

【问题讨论】:

    标签: python search python-2.7


    【解决方案1】:
    r = re.compile(r"\b%s" % re.escape(word))
    for line in openfile:
        hit = r.search(line)
        if hit:
            # whatever
    

    说明:这会从\b(字边界)和考虑中的word 构建一个正则表达式,然后在文件的每个line 中搜索它。它会在该行中找到以word 开头的第一个单词并返回一个regexp match object

    【讨论】:

    • 对不起,我像个白痴一样漏掉了 findline 的定义: def findline(word,linz): for line in linz: if word in line: return line 感谢 larsmans,我会给它一个尝试并报告!
    • 好的,试过了,得到三个这样的响应:<_sre.sre_match object at>
    • def find(word, letter): index = 0 while index
    猜你喜欢
    • 1970-01-01
    • 2012-01-11
    • 2014-09-27
    • 2010-12-12
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 2012-09-27
    • 2011-03-13
    相关资源
    最近更新 更多