簡體   English   中英

如何在列表中查找和總結所有匹配的單詞?

[英]How to find and sum up all with the matching words on a list?

EmpRecords=[1,'Angelo','Fabregas','South','City',
           2,'Fabian','Fabregas','North','City',
           3,'Griffin','De Leon','West','City',
           4,'John','Doe','East','City',
           5,'Jane','Doe','Southville','Town']

Output 應該是這樣的:

Enter word to search: Doe
Same words: 2

我該怎么做呢? 我還應該澄清一下,EmpRecords 實際上只是一個轉換為列表的文本文件。

所以它實際上是:

EmpRecords='''1,Angelo,Fabregas,South,City;
           2,Fabian,Fabregas,North,City;
           3,Griffin,De Leon,West,City;
           4,John,Doe,East,City;
           5,Jane,Doe',Southville,Town'''

也許這與找到匹配詞有關?

假設您要搜索以逗號分隔的任何單詞,並且每一行都是一個單獨的項目:因為您的實際記錄是用“;”分隔的您需要創建一個嵌套列表,如下所示:

>>> record_groups = EmpRecords.split(";")
>>> final_groups = [each_group.split(",") for each_group in record_groups]

稍后您可以搜索給定單詞的列表項:

>>> word = "Doe"
>>> counter = 0
>>> for each_entry in final_groups:
        if word in each_entry:
            counter += 1        
>>> print(counter)

方法 2:

如果它已經在文件中,您可以直接逐行打開並搜索:

word = "Doe"
counter = 0
with open("input.txt") as fd:
    for line in fd:
        if word in line.strip().split(",")
            counter += 1
print(counter)

如果要從文件中讀取並計數,可以使用循環。

import csv
with open('records.txt') as csvfile:
    linereader = csv.reader(csvfile, delimiter=',')
    count = 0;
    target_value = 'Doe'
    for row in linereader:
        if row[2] == target_value:
            count += 1;

print("Count: ",count)

如果您要使用數據,您可能需要從最后一個字段中刪除分號 (;)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM