Home > Blockchain >  How to delete brackets and text within them python
How to delete brackets and text within them python

Time:06-27

I am generating a text file the contents looks like this

[AnyTextOrNumber]AnyTextOrNumber#AnyNumber

How can I generate the file so it always looks like this

AnyTextOrNumber#AnyNumber

I just want to get the text file generated without the brackets and contents within them

CodePudding user response:

Here's how you could do it with slicing:

input_file = "file_input.txt"
output_file = "file_output.txt"

# Open 2 files, 1 for reading, 1 for writing
with open(input_file, "r") as in_file, open(output_file, "w") as out_file:
    for row in in_file:
        # Remove newlines
        row = row.strip()
        # find "#"
        number_index = row.find("#")
        # slice from string
        any_number = row[number_index:]
        # find "]" and slice
        string_index = row.find("]")
        any_string = row[1:string_index]
        # Format new line and write to file
        out_file.write(f"{any_string}{any_number}\n")

CodePudding user response:

You can use re to achieve the desired result.

I've used two patterns and different string scenarios and their behavior. You can see the limitations we can have and chose whichever suits your purpose the best.
You could use something like this :

import re

str1 = "[AnyTextOrNumber]AnyTextOrNumber#AnyNumber"
str2 = "[AnyTextOrNumber]AnyTextOrNumber#AnyNumber[MoreTextOrNumber]"
str3 = "[AnyTextOr]Number]AnyTextOrNumber#AnyNumber"
str4 = "[AnyTextOr]Number]AnyTextOrNumber#AnyNumber[MoreTextOrNumber]"

pattern1 = r'\[[^()]*\]'
pattern2 = r'\[.*?\]'

convPattern1_str1 = re.sub(pattern1, '', str1)
convPattern1_str2 = re.sub(pattern1, '', str2)
convPattern1_str3 = re.sub(pattern1, '', str3)
convPattern1_str4 = re.sub(pattern1, '', str4)

convPattern2_str1 = re.sub(pattern2, '', str1)
convPattern2_str2 = re.sub(pattern2, '', str2)
convPattern2_str3 = re.sub(pattern2, '', str3)
convPattern2_str4 = re.sub(pattern2, '', str4)

print(convPattern1_str1) #Will give AnyTextOrNumber#AnyNumber
print(convPattern1_str2) #Will remove everything
print(convPattern1_str3) #Will give AnyTextOrNumber#AnyNumber
print(convPattern1_str4) #Will remove everything

print(convPattern2_str1) #Will give AnyTextOrNumber#AnyNumber
print(convPattern2_str2) #Will give AnyTextOrNumber#AnyNumber
print(convPattern2_str3) #Will give Number]AnyTextOrNumber#AnyNumber
print(convPattern2_str4) ##Will give Number]AnyTextOrNumber#AnyNumber
  • Related