【问题标题】:Python 3 searching for a keyword more than once per line in a text filePython 3 在文本文件中每行不止一次搜索关键字
【发布时间】:2016-05-04 23:17:13
【问题描述】:

处理一个在特定文件中搜索关键字的简单脚本。一旦找到关键字,它就会计算它被使用的次数,然后将每次找到关键字的行号记录到一个列表中。然后打印出它被找到的次数和在哪几行。 该程序对关键字进行计数,但在一行中找到一次后,它会转到下一行。它不计算多个关键字。我知道它这样做是因为 if 语句:if keyword in line: Number_Of_Key_Words = Number_Of_Key_Words + 1 found_at.append(num) continue

如何让它考虑文件每行可能存在的多个关键字?

完整代码:

def search():
Number_Of_Key_Words = 0
found_at = [];
keyword = input("Enter a key word to search for: ")
with open("WordList.txt") as file:
    for num, line in enumerate(file, 1):
        if keyword in line:
            Number_Of_Key_Words = Number_Of_Key_Words + 1
            found_at.append(num)
            continue
    print(Number_Of_Key_Words)
    print("Found on lines: ", found_at)
search()

示例 单词表

单词单词单词

搜索“单词” 输出:1
在第 [1] 行找到

想要: 输出:3
在第 [1] 行找到

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    一种方法是使用re 模块findall,它会在字符串中找到所有出现的地方。

    类似这样的东西(我也提出了一些改变):

    import re
    
    keyword = input("...")
    found_at = []
    counter = 0  # Number_Of_Key_Words is not a good python name
    # file is a PY2 built in, so I use 'f' instead
    # also you should be explicit for the open mode, 'r' == read mode
    with open("...", "r") as f:
        for num, line in enumerate(f, 1):
            # re.findall() will return a list of all keyword occurrence
            # len() will then measure the occurrence effectively
            count = len(re.findall(keyword, line))
            if count > 0:  # ie. keyword in line at least once
                found_at.append(num)
                counter += count
    
        print(found_at)
        print(counter)
    

    希望这会有所帮助。

    【讨论】:

    • @Tommy,就像dreamzboy's answer using string count() 也是一个好主意,但如果您需要搜索关键字忽略大小写或模式匹配等,您可能会从re 模块中受益更多。 ,阅读docs here。你应该探索和尝试更多,向所有人学习。
    【解决方案2】:

    或者,您可以使用“str.count (keyword, start, end)”

    样本数据“wordtext.txt”:

    red, blue, red, green.
    blue, yellow, white.
    green, orange.
    red, blue, green, red, black, yellow, red.
    

    输出:

    >>> with open ('wordtext.txt') as f:
        for i, line in enumerate (f):
            found = line.count ('red')
            if found:
                print ('Line: %d  Red: %d' % (i, found))
    
    
    Line: 0  Red: 2
    Line: 3  Red: 3
    >>> 
    

    【讨论】:

    • 我不得不承认re.findall() 的答案是我的第一个倾向,但这肯定更优雅。
    • 需要修复枚举的起始位置,否则该行将偏移 1。另外,在文件读取模式下明确是个好主意
    • RE 模块确实非常强大,但为什么在不需要的时候导入呢? =)
    • @dreamzboy,你说得对,在这种情况下,OP 不需要re 模块,这只是解决问题的另一种方式。从他的语法和命名转换来看,他显然来自 C 系列语言,我相信这将受益于阅读更多不同的示例并学习阅读 Python 文档并尽可能多地探索/采用
    • @Anzel - 你提到“C-family”很有趣。这也是我开始的地方。我同意采用不同的方法是有益的,因此感谢您的贡献。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    相关资源
    最近更新 更多