Home > database >  How to find and sum up all with the matching words on a list?
How to find and sum up all with the matching words on a list?

Time:12-12

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 should something be like:

Enter word to search: Doe
Same words: 2

How do I do this? I should also clarify that EmpRecords is actually just a text File that is converted into a list.

so it's actually:

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

Maybe this has something to do with finding the matching words?

CodePudding user response:

Assuming you want to search for any word separated by comma and each line is a separate item: Since your actual records are separated by ";" you need to create a nested list as below:

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

Later you can search through list items for the given word:

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

APPROACH 2:

If it is already in a file you can directly open line by line and search:

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

CodePudding user response:

If you want to read from the file and count, you can use a loop.

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)

You may need to remove the semicolon (;) from the last field if you will be using the data.

  • Related