python正则表达式搜索文件中的常规模式

时间:2014-04-02 01:04:45

标签: python-2.7

我想要一个函数在文件内的每一行上找到一个模式(单词字符)。我的代码有点工作,但在阅读第一行后它没有进一步发展。有人可以帮忙吗?导入重新

    inputtext = open('input.txt', 'r+')
    inputtext1 = inputtext.read()


    match = re.search(r'([matchwordinline].*\n)+', inputtext1)



    if match:

            match1 = match.group()
    print match1

1 个答案:

答案 0 :(得分:1)

re.search只匹配一个实例..尝试re.findall

list_name = re.findall(r'([matchwordinline].*\n)+', inputtext1)

了解更多 访问https://docs.python.org/2/library/re.html?highlight=matching%20searching#finding-all-adverbs

import re
inputtext = open('input.txt', 'r+')
inputtext1 = inputtext.read()

match = re.findall(r'([your word].*\n)+', inputtext1)
print match

这是我的input.txt

cat
alicecat deaf
cut cat crazy
buttercup ruin
youseeacatidont

当我搜索单词cat时,我得到以下输出

['cat\n', 'cat deaf\n', 'cat crazy\n', 'catidont\n']

希望这就是你的意思..

相关问题