how to write a line to read a certain sentence in a text file?

Viewed 85

I am currently learning how to code python and i need help with something. is there a way where I can only allow the script to read a line that starts with Text = .. ?

Because I want the program to read the text file and the text file has a lot of other sentences but I only want the program to focus on the sentences that starts with Text = .. and print it out, ignoring the other lines in the text file.

for example,

in text file:

min = 32.421
text = " Hello I am Robin and I am hungry"
max = 233341.42

how I want my output to be:

Hello I am Robin and I am hungry

I want the output to just solely be the sentence so without the " " and text =

This is my code so far after reading through comments!

import os
import sys
import glob
from english_words import english_words_set

try:
    print('Finding file...')
    file = glob.glob(sys.argv[1])
    print("Found " + str(len(file)) + " file!")
    print('LOADING NOW...')
    
    with open(file) as f:
        lines = f.read()

         for line in lines:
              if line.startswith('Text = '):
                 res = line.split('"')[1]
                 print(res)
4 Answers

You can read the text file and read its lines like so :

# open file
with open('text_file.txt') as f:
    # store the list of lines contained in file
    lines = f.readlines()
    
    for line in lines:
        # find match
        if line.startswith('text ='):
            # store the string inside double quotes
            res = line.split('"')[1]
            print(res)

This should print your expected output.

You can open the file and try to find if the word "text" begins a sentence in the file and then checking the value by doing

file = open("file.txt", "r") # specify the variable as reading the file, change file.txt to the files path
for line in file: # for each line in file
    if line.startswith("text"): # checks for text following a new line
        text = line.strip() # removes any whitespace from the line
        text = text.replace("text = \"", "") # removes the part before the string
        text = text.replace("\"", "") # removes the part after the string
        print(text)

Or you could convert it from text to something like yml or toml (in python 3.11+) as those are natively supported in python and are much simpler than text files while still keeping your file system about the same. It would store it as a dictionary instead of a string in the variable.

List comprehensions in python: https://www.youtube.com/watch?v=3dt4OGnU5sM

Using list comprehension with files: https://www.youtube.com/watch?v=QHFWb_6fHOw

First learn list comprehensions, then the idea is this:

listOutput = ['''min = 32.421
text = "Hello I am Robin and I am hungry"
max = 233341.42''']

myText = ''.join(listOutput)

indexFirst= myText.find("text") + 8 # add 8 to this index to discard {text = "}
indexLast =  myText.find('''"''', indexFirst) # locate next quote since indexFirst position

print(myText[indexFirst:indexLast])

Output:

Hello I am Robin and I am hungry

with open(file) as f:
    lines = f.read().split("\n")
    
    prefix = "text = "
    for line in lines:
        if line.startswith(prefix):
            # replaces the first occurence of prefix and assigns it to result
            result = line.replace(prefix, '', 1)
            print(result)

Alternatively, you could use result = line.removeprefix(prefix) but removeprefix is only available in python3.9 upwards

Related