Python Forum
Replace characters from file in Python 2.7 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Replace characters from file in Python 2.7 (/thread-15860.html)



Replace characters from file in Python 2.7 - melmouja - Feb-03-2019

Hello

I can't replace more strings from file, i use two ways:
  • function lambda
  • expr regulier

#! /bin/python
import re
import sys
import fileinput
import os
stripped = lambda s: "".join(i for i in s if 31 < ord(i) < 127)
#en dur ça marche
print(stripped('\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah'))
 
for line in fileinput.input('fic.txt'):
    #with exrp regu
    line1 = re.sub(r'[^\x00-\x7f]', r'', line.rstrip())
    print(line1)
    ####################
    #with lambda
    print(stripped(line.rstrip()))
Output:
>cat fic.txt \xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah
Thanks for help


RE: Replace characters from file in Python 2.7 - ichabod801 - Feb-04-2019

What exactly are you trying to do? I'm not sure what result you are trying to get.


RE: Replace characters from file in Python 2.7 - melmouja - Feb-04-2019

Hello,
I use three methods to replace "\xe2\x80\x9c and" "\xe2\x80\x9d" :
The first give me a good result
stripped = lambda s: "".join(i for i in s if 31 < ord(i) < 127)
#en dur ça marche
print(stripped('\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah'))
Output:
http://www.google.com blah blah#%#@$^blah
but the others not ok
for line in fileinput.input('fic.txt'):
    #with exrp regu
    line1 = re.sub(r'[^\x00-\x7f]', r'', line.rstrip())
    print(line1)
    ####################
    #with lambda
    print(stripped(line.rstrip()))
Output:
\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah \xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah
I thank it's clear now.

Thanks for help