简体   繁体   中英

Python to extract parts of data from a file

I have data that looks like this

{sdfsdfsdfsdfsdf}{sdfsdfsdfsfsdfsdf}{dfsdfsdfsdfsdfsf}{dfsdfsdfsfsdfsd}

I want a peace of code that can turn it into this

{sdfsdfsdfsdfsdf}
{sdfsdfsdfsfsdfsdf}
{dfsdfsdfsdfsdfsf}
{dfsdfsdfsfsdfsd}

any help will be appreciated thank you

You can split on } and add it back to each split line slicing off the last } or use re.findall to match curly braces with anything in between:

lines = """{sdfsdfsdfsdfsdf}{sdfsdfsdfsfsdfsdf}{dfsdfsdfsdfsdfsf}{dfsdfsdfsfsdfsd}"""

print("\n".join([line+"}" for line in lines.split("}")][:-1]))

{sdfsdfsdfsdfsdf}
{sdfsdfsdfsfsdfsdf}
{dfsdfsdfsdfsdfsf}
{dfsdfsdfsfsdfsd}

import  re

print("\n".join(re.findall("(\{.*?\})",lines)))

{sdfsdfsdfsdfsdf}
{sdfsdfsdfsfsdfsdf}
{dfsdfsdfsdfsdfsf}
{dfsdfsdfsfsdfsd}

From a file:

    with open("foo.txt") as f:
        for line in f:
             print("\n".join(re.findall("(\{.*?\})",line)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM