Remove specific chars in text file Python

Viewed 50

I am searching some specific strings, however; I find it in places where it shouldn't be. Because I convert pdf files to .txt using html. I found some pattern that I can reach string which i dont want it.

This is the string I want to delete "6\n5\n4\n3\n2\n1\nD\nC\nB\nA" . I am looking " \nC\n" in some other text block not here. So if i find pattern " \nC\nB", I can delete but how I don't figure out. I write inplace_change function but i got error message like this.

"subprocess.CalledProcessError: Command '['java', '-jar', 'C:\Users\Kronos\AppData\Roaming\Python\Python310\site-packages\tabula\tabula-1.0.5-jar-with-dependencies.jar', '--pages', '1', '--guess', '--format', 'JSON', '383026_C.pdf']' returned non-zero exit status 1."

def findWordInText(name):
    a = name+".txt"
    count =0   
    with open(a,'r',encoding='utf-8',errors="ignore") as f:  
        line = f.read()
        i = 0
        if(r"\nC\n")in line:
            String = r"\nC\n" 
            ch ="B"
            if (String+ch) in line:
                print('Need to remove')
                txt = String+ch  
                f.close()       
                inplace_change(a,txt,"removed")                
                     
            with open(a,'r',encoding='utf-8',errors="ignore") as f:  
                line = f.read()                                                        
                if(r"\nC\n") in line:
                    txt="C"
                    writeOnExcel(name,txt)
                    count +=1
def inplace_change(file,old,new):
    with open(file) as f:
        s = f.read()
        if old not in s:
            print('"{old_string}" not found in {filename}.'.format(**locals()))
            return
    with open(file, 'w') as f:
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old, new)
        f.write(s)
1 Answers

If you have something like a string with alot of newline characters followed by a character like a number or letter, you can use regex to substitute them with an empty string, instead of going through it line by line, you can go through them all at once like this.

a = r"""python
\na\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\nx\ny\nz
\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0Message Here\na\nb\nc\nd\ne
\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nPSome Other Message\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ
\n!\n@\n$\n%\n^\n&\n*\n(\n)\n_\n-\n=\n+\n{\n}\n[\n]\n|\n;\n:\n'\n,\n.\n<\n>\n?\n/\n`\n~
"""

# regex to clear \n followed by a character
import re
a = re.sub(r"\\n[^\\]", "", a)
print(a)

Output:



Message Here
Some Other Message


Related