【问题标题】:Python Search File For Specific Word And Find Exact Match And Print LinePython搜索特定单词的文件并找到精确匹配并打印行
【发布时间】:2016-12-22 18:17:38
【问题描述】:

我编写了一个脚本来打印包含圣经 txt 文件中特定单词的行。问题是我无法得到该行的确切单词,而是打印该单词的所有变体。

例如。如果我搜索“am”,它会打印包含“lame”、“name”等单词的句子。 相反,我希望它只打印带有“am”的句子

即“我是你的救世主”、“我在这里”等

这是我使用的代码:

import re
text = raw_input("enter text to be searched:")

shakes = open("bible.txt", "r")

for line in shakes:
    if re.match('(.+)'  +text+  '(.+)', line):
        print line 

【问题讨论】:

    标签: python-2.7


    【解决方案1】:

    这是完成任务的另一种方法,虽然它不太遵循您当前的方法,但它可能会有所帮助。

    我输入的 test.txt 文件有四个句子:

    This is a special cat. And this is a special dog. That's an average    cat. But better than that loud dog.
    

    运行程序时,请包含文本文件。在命令行中,这看起来像:

    python file.py test.txt
    

    这是随附的file.py:

    import fileinput
    
    key = raw_input("Please enter the word you with to search for: ")
    #print "You've selected: ", key, " as you're key-word."
    
    with open('test.txt') as f:
        content = str(f.readlines())
    
    #print "This is the CONTENT", content
    
    list_of_sentences = content.split(".")
    for sentence in list_of_sentences:
        words = sentence.split(" ")
        for word in words:
            if word == key:
                print sentence
    

    对于关键字“cat”,返回:

    That is a special cat
    That's an average cat
    

    (注意句号不再存在)。

    【讨论】:

    • 如何将 txt 文件“bible.txt”作为输入并将 raw_input 变量分配给 key。谢谢
    • 有几种方法可以解决这个问题,例如逐行或一次获取所有内容。此版本一次获取所有内容。我已经更新了上面显示这一点的示例。
    【解决方案2】:

    我想如果你在text 之外的字符串中,像这样放置空格:

    '(.+) ' + text + ' (.+)'
    

    如果我正确理解代码中发生的事情,那就可以了。

    【讨论】:

    • 感谢 SparklePony 成功了。我是新手,刚刚开始。你能解释一下这段代码有什么区别吗?
    • 此代码的不同之处在于它搜索带有“am”一词且周围有空格的句子。如果您仔细查看text 周围的字符串,则会添加空格,因此基本上这会阻止它找到“ham”,因为前面没有空格。我希望这个答案有意义。
    • 另外,如果您喜欢,可以单击此答案旁边的复选标记吗?当你这样做时,这意味着你喜欢给出的答案。 (我得到了声誉。)
    • 对不起,我是 stackoverflow 的新手,不知道滴答声
    【解决方案3】:

    re.findall 在这种情况下可能有用:

    print re.findall(r"([^.]*?" + text + "[^.]*\.)", shakes.read())
    

    甚至没有正则表达式:

    print [sentence + '.' for sentence in shakes.split('.') if text in sentence]
    

    阅读此文本文件:

    I am your saviour. Here I am. Another sentence.
    Second line. 
    Last line. One more sentence. I am done.
    

    两者都给出相同的结果:

    ['I am your saviour.', ' Here I am.', ' I am done.']
    

    【讨论】:

    • 感谢帮助但出现错误 "Type error:Expected string or buffer" "Return _compile(pattern,flags).findall(strings)"
    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多