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
CodePudding user response:
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.
CodePudding user response:
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
CodePudding user response:
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)