simplify my code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

10th Sep 2021, 6:31 PM
crygo
crygo - avatar
3 Answers
+ 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)
10th Sep 2021, 7:13 PM
Ratnapal Shende
Ratnapal Shende - avatar
+ 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 :)
10th Sep 2021, 7:11 PM
DavX
DavX - avatar
+ 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)
10th Sep 2021, 7:25 PM
DavX
DavX - avatar