-1

This is the text file we need to extract the particular string from the text file using python or pandas Single quotes are present in that string

>>>>>>>>>>>>
[fgh: hello how r u 'Output Port 1' of 'abcd/cdf' at the home]
[bsdfglsdgjh flgdfhgdfgh]
[fgh: mzjdhxl sldhvlk hvljhxv 'name1']
[bsdfglsdgjh flgdfhgdfgh]
---
[fgh: hello how r u 'Output Port 1' of 'cdf/abc' at the home]
[bsdfglsdgjh flgdfhgdfgh]
[fgh: mzjdhxl sldhvlk hvljhxv 'name2']
[bsdfglsdgjh flgdfhgdfgh]
---
[fgh: hello how r u 'Output Port 1' of 'xyz/pmn' at the home]
[bsdfglsdgjh flgdfhgdfgh]
[fgh: mzjdhxl sldhvlk hvljhxv 'name3']
[bsdfglsdgjh flgdfhgdfgh]

The output should be

name1 : abcd/cdf
name2 : cdf/abc
name3 : xyz/pmn
3

3 Answers 3

0

the answer to your question is this:

with open("filename.txt", "r") as file:
    strt = file.read()

a = strt.split("---")
for item in a:
    b = item.split("'")
    a = b[5].replace(">>>>>>>>>>>>", "")
    print(f"{b[5]} : {b[3]}")

Put all your content into filename.txt and run it.

1
  • For large data IndexError: list index out if range error is coming
    – DCompany
    Commented Jan 18, 2023 at 0:16
0

just open and read each line and get the values you need

with open("example.txt", "r") as example:
nameNum = 1
for i in example.readlines():
    
    if "Output Port 1" in i:
        new = i.split("'")
        index = new.index("Output Port 1")
        print(f'name{nameNum} : ' + new[index+2])
        nameNum += 1
0

do you know about regular expressions? While not overly performant they are exactly the type of thing you would use in such a situation.

something along the following lines should give you an option to find the names.

import re

match_lines_with_content = re.compile(r"^[fhg:")
match_name_designated_by_single_quote = re.compile(r"mzjdhxl sldhvlk hvljhxv (?P<name>[^']+)")

for line in <input_lines>:
   if match_lines_with_content.matches(line):
        name = match_name_designated_by_single_quote.match(line).group(0)
   
2
  • mzjdhxl sldhvlk hvljhxv is probably a placeholder to indicate variable text. Commented Jan 17, 2023 at 16:53
  • Agreed, though I did not feel confident enough to assume single quotes were the sole identifying elements for the searched string. Do you have a suggestion for a better regex? r"[^']+(?P<name>[^']+)" ? Commented Jan 17, 2023 at 17:08

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.