I'm trying to run the method below against a very large corpus and I need to optimize/reduce the run time for this method as it already takes up about 6 seconds to execute.
- Check the word only consist of alphabets, hyphen and apostrophe
- First character of word must be alphabet
- Last character of word must be alphabet or apostrophe only
- Use of re library (regex) strictly not allowed
def delUnknownChar(w): wf =  for c in w: if (c == "'" or c == "-" or c.isalpha()): wf.append(c) w = "".join(wf) wf.clear() if (len(w) > 1): while(not w.isalpha()): w = w[1:] while (w[-1] == "-"): w = w[:-1] return w else: return None string1 = delUnknownChar("-'test'-") print(string1)
Output will be test' The code above will take about 5 seconds to run.
If I change lines 2-7 of the code to this line:
w = "".join(c for c in w if c == "'" or c == "-" or c.isalpha())
The runtime somehow increases by 1 more second.
Does anyone here have a better idea or an improved optimized way to check for this at a much faster speed?