For instance, I want to return all rows that have the term "Liverpool", but i cannot use Pandas to do so. Sample of contents of text file is given below:
abcd,Liverpool, xyz
mancity, Liverpool
Liverpaul, city
Liverpool, football
How do I return the rows that have the particular term?
CodePudding user response:
Just use some file handling operations like this
with open(r"path\to\text\file\file.txt", "r") as reader:
# Read the first line
line = reader.readline()
# Keep reading till the last line
while line:
# Whenever you encounter Liverpool, make a note of it
if "Liverpool" in line:
print(line)
line = reader.readline()
CodePudding user response:
You can use the regex module to handle this Read the csv file into a variable with each new row as a string item in the list then with code that looks like this.
Import re
matches = []
liverfinder = re.compile('Liverpool')
for row in file:
search = liverfinder.search(row)
if liverfinder:
matches.append(row)
CodePudding user response:
If the contents you mentioned are in a csv file then use the python's inbuilt csv
module(https://docs.python.org/3/library/csv.html).
You can use it like how you would use a normal file.
with open('your_csv_file.csv', 'r') as input:
# create a reader for your file
input_reader = csv.reader(input, delimiter=',')
# all the lines can be read by iteration
for line in input_reader:
# since all the values a line in a csv file are separated by comma, they are read as a list
# so your first line would be in the format: ['abcd', 'Liverpool', 'xyz']
# so you can search for liverpool like this:
if 'liverpool' in line:
print(line)
Using the csv reader instead of a normal reader for csv files can really help while dealing with csv files.