keep all alphabetic and numeric characters in python

Viewed 100

i have a file.txt and i just want to keep all alphabetic and numeric characters without whitespace and save it in a list, is there another way to do it? this is the new code, is faster. what do you think about it?

fin = open(fcompiti, encoding = 'UTF-8')
s = fin.read()
s = s.replace(' ', '').replace('\n','')
4 Answers

I think it would be a little fast:

import re, string

pattern = re.compile('[\W_]+')

with open('file.txt') as f:
    rdstr = f.read()

rdstr = pattern.sub('', rdstr)

print(rdstr)

For this txt file:

abc342][][]asde34=)$(s)

it will return

abc342asde34s

You can watch it in live here https://repl.it/Ni04/0

You can try with a regex, which may or may not be faster than your approach (depending on the size and structure of your text).

import re

with open('file.txt') as f:
    s = f.read()

s = ''.join(re.findall(r'[\dA-z]+', s))

As a side note, your code is not as memory efficient as it could be. Instead of creating a list in memory and then passing it to join you can use a generator.

s = ''.join(c for c in s if c.isalpha() or c.isnumeric())
# note absence of square brackets

Regex (regular expressions) are your friend.

fin = open('file.txt')
s = fin.read()
alphanums = re.sub(r'[\W_]+', '', s)

This answer will give you more knowledge and examples on how and why this works.

outside of using RegEx, you could also use the .isalnum() builtin function instead of checking .isalpha() and .isnumeric()

with open('file.txt') as fin:
    s = fin.read()
    s = ''.join(c for c in s if c.isalnum())

EDIT: as another user mentioned, you can remove the part that is creating a list of the characters in the file before joining them. the [, ] brackets inside of the .join() aren't necessary.

Related