Home > OS >  Python find word in a rows and append this in a new text file
Python find word in a rows and append this in a new text file

Time:10-13

I use jupyter notebook with pandas, I would like to find a recurring word of my choice in a large file, then select the rows and paste it or append on another text file, e.g with the word "test".:

this is a test sample line
this is a second example line
this is a third example line
this is a test fourth sample line
this is a final example line

and get on a new text file only the lines in which the word "test" is present:

this is a test sample line
this is a test fourth sample line

How could I achieve this in python using jupyter to make things easier?

PS. it would be perfect if you could read from multiple text files and append the rows without overwriting them!

Thanks as always!

CodePudding user response:

Assuming the following dataframe as input:

                                 col
0         this is a test sample line
1      this is a second example line
2       this is a third example line
3  this is a test fourth sample line
4       this is a final example line

You could use str.contains:

df[df['col'].str.contains(r'\btest\b', regex=True)]

output:

                                 col
0         this is a test sample line
3  this is a test fourth sample line
  • Related