1

I have been given the task to remove all non numeric characters including spaces from a text file and then print the new result next to the old characters for example:

Before:

sd67637 8

ssheiej44

After:

sd67637 8 = 676378

ssheiej44 = 44

As i am a beginner i do not know where to start with this task. I followed instructions from another user but i wasnt as clear to elaborate this is what i have so far.

text1 = open('/Users/student/Desktop/Harry.txt', 'r')
data = text1.readlines()
new_string = ''.join(ch for ch in data if ch.isdigit())
print(data, '=', new_string)

Yet it still doesnt give me the desired effect as shown above. Instead i get this:

    [] = 

Could someone please fix this and explain in laymens terms please.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Obcure
  • 961
  • 3
  • 11
  • 22
  • Just answered your [same question](http://stackoverflow.com/questions/17336943/removing-non-numeric-characters-from-a-string) - [here](http://stackoverflow.com/a/17337324/1561176) – Inbar Rose Jun 27 '13 at 07:45
  • You are opening an empty file, or need to reopen it. If your code is printing `[]` for `data`, then `.readlines()` returned an *empty list*. – Martijn Pieters Jun 27 '13 at 07:49

2 Answers2

3

You did not call the text1.readlines method. Add ():

data = text1.readlines()

Note that a file object such as text1 can work as an iterator. There is no need to call .readlines(); just loop over text1 directly. Your code still needs adjustment; both .readlines() and text1 give you a sequence of lines:

for line in text1:
     new_string = ''.join(ch for ch in line if ch.isdigit())
     print(data, '=', new_string)

In your version, ch was assigned a whole line from the file at a time, and since each line contains at least a newline, .isdigit() would always be False.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Pretty much the same answer I gave you on your previous question here.

from string import ascii_letters

with open('/Users/student/Desktop/Harry.txt') as f:
    for line in f:
        print (line, '=', line.translate(None, ascii_letters+' '))
Community
  • 1
  • 1
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131