0
simplify my code
How to change code that non alphabetical 'word' would'nt be in list of values? Also tell me how to simplify my code. It takes a lot of time for bigger texts https://code.sololearn.com/cT3G45NV9tAS/?ref=app
3 odpowiedzi
+ 2
#if you are trying to pick alphabetical words from a txt file into your list then you can do like this :
with open("filename.txt",'r') as fp:
words=[i.lower() for i in fp.read().split() if i.isalpha()]
print(words)
+ 1
Would love to help, however can you provide a sample input and expected output...
From your question, I think you want to alter a list to remove all non alpha characters...do you want to keep these items but remove the offending chars?
You could use regex to do this, happy to refactor for you if you explain more :)
+ 1
#if you are trying to create a new list, containing all items but removing non-alpha chars:
import re
listex = ["Test", "@word", "fi!;sh"]
newlist = [re.sub("[^ \w]","", x).strip().lower() for x in listex]
print(newlist)