python - Removing white spaces and punctuation from list -
def wordlist (l: list) -> list: '''returns wordlist without white spaces , punctuation''' result = [] table = str.maketrans('!()-[]:;"?.,', ' ') x in l: n = x.translate(table) n = x.strip() n = x.split() if n != []: result.extend(n) return result the function supposed work this:
print(wordlist([' testing', '????', 'function!!'])) should yield:
['testing', 'function'] but code have above yields:
['testing', '??', 'function!!'] so assume i'm doing incorrectly code in regards removing punctuation--where should fix it? other suggestions simplify code appreciated (since figured it's bit long-winded).
did mean chain translate(table), strip() , split() calls?
then
n = x.translate(table) n = x.strip() n = x.split() should be
n = x.translate(table) n = n.strip() # change x n n = n.split() # same here or
n = x.translate(table).split() no need intermediate strip().
as further simplification, don't have check emptiness of n, looks premature optimization me:
if n != []: # can remove line result.extend(n) the result:
def wordlist (l: list) -> list: '''returns wordlist without white spaces , punctuation''' result = [] table = str.maketrans('!()-[]:;"?.,', ' ') x in l: result.extend(x.translate(table).split()) return result you can replace loop list comprehension.
Comments
Post a Comment