【问题标题】:how to find a word in python如何在python中找到一个单词
【发布时间】:2013-08-05 10:09:30
【问题描述】:

我正在尝试在文件中搜索并找到正确的单词

 file = ('data.bin', '+r')
 Filefind = file.read()
 f = raw_input("search a word: ")
 While f in Filefind:
        print "this word is found!"

此代码实际上找到了我输入的单词,但即使没有完全输入它也会找到该单词 例如,如果我在文件中有“findme”字,如果我在 raw_input 中只输入“fi”,脚本就会找到它

如果在文件中找到完整的单词,如何编写返回 True 的脚本?

【问题讨论】:

    标签: python file search


    【解决方案1】:

    使用带有字边界的regex

    import re
    def search(word, text):
        return bool(re.search(r'\b{}\b'.format(re.escape(word)), text))
    ... 
    >>> search("foo", "foobar foospam")
    False
    >>> search("foo", "foobar foo")
    True
    

    【讨论】:

    • 请解释我如何在文件上使用这个正则表达式,我从未在 Python 中使用过它们
    • @Streak 有什么问题?只需将文件内容和您要搜索的单词传递给此函数。
    • 好的,但我收到以下错误:'str' object has no attribute 'format'
    猜你喜欢
    • 2021-05-30
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 2020-06-23
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多