Home > database >  How do I find multiple strings in a text file?
How do I find multiple strings in a text file?

Time:01-21

I need all the strings found in the text file to be found and capitalized. I have found out how to find the string but getting multiple is my issue if you can help me print, where the given string is throughout my code, would be great thanks.

import os
import subprocess

i = 1
string1 = 'biscuit eater'

# opens the text file

# if this is the path where my file resides, f will become an absolute path to it
f = os.path.expanduser("/users/acarroll55277/documents/Notes/new_myfile.txt")

# with this form of open, the wile will automatically close when exiting the code block
txtfile = open (f, 'r')

# print(f.read()) to print the text document in terminal
# this sets variables flag and index to 0

flag = 0
index = 0

# looks through the file line by line
for line in txtfile:
    index  = 1

#checking if the sting is in the line or not
    if string1 in line:
        flag = 1
        break 
# checking condition for sting found or not
if flag == 0:
    print('string '   string1   ' not found')
else:
    print('string '   string1   ' found in line '   str(index))

CodePudding user response:

I believe your approach would work, but it is very verbose and not very Pythonic. Try this out:

import os, subprocess

string1 = 'biscuit eater'

with open(os.path.expanduser("/users/acarroll55277/documents/Notes/new_myfile.txt"), 'r ') as fptr:

    matches = list()
    [matches.append(i) for i, line in enumerate(fptr.readlines()) if string1 in line.strip()]
    fptr.read().replace(string1, string1.title())

    if len(matches) == 0: print(f"string {string1} not found")

    [print(f"string {string1} found in line {i}") for i in matches]

This will now print out a message for every occurrence of your string in the file. In addition, the file is handled safely and closed automatically at the end of the script thanks to the with statement.

CodePudding user response:

You can use the str.replace-method. So in the line where you find the string, write line.replace(string1, string1.upper(), 1). The last 1 is there to only make the function replace 1 occurence of the string.

Either that or you read the text file as a string and use the replace-method on that entire string. That saves you the trouble of trying to find the occurence manually. In that case, you can write

txtfile = open(f, 'r')
content = txtfile.read()
content = content.replace(string1, string1.upper())
  •  Tags:  
  • Related