Python 3在文本文件中每行搜索一次以上的关键字

时间:2016-05-04 23:17:14

标签: python-3.x

处理在某个文件中搜索关键字的简单脚本。一旦找到关键字,就会计算它的使用次数,然后记录每次找到关键字到列表时的行号。然后打印出它找到的次数和行数。 该程序对关键字进行计数,但在一行中找到一次后,它会转到下一行。它不会计算多个关键字。我知道这是因为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]

上找到

2 个答案:

答案 0 :(得分:1)

一种方法是使用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) ,它会在字符串中找到所有匹配项。

这样的事情(我也提出了一些改变):

<?php
//Assuming that $data holds all the elements of your specific name attribute
$data = $_POST; 
for ($i=0;$i <= count($data);$i++) {
$pdf->Cell($i); //Here you can do whatever you want with your cell
}
?>

希望这有帮助。

答案 1 :(得分:1)

或者,您可以使用&#34; str.count(关键字,开头,结尾)&#34;

示例数据&#34; wordtext.txt&#34;:

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
>>>