3 ms·
I thought it was trivial to understand, though the comment above it helps a lot, and it's maybe an unfair advantage that I'd done the same thing in pretty much
by kragen 4y ago
I thought it was trivial to understand, though the comment above it helps a lot, and it's maybe an unfair advantage that I'd done the same thing in pretty much the same way four years ago. It probably depends on your background; I wouldn't write it that way for people who didn't know shell, just like I wouldn't write this comment in English for people who speak only Spanish.
I'm not convinced that it's easier to understand in Python (even though I simplified it a bit, in part because one piece of the Python 3 braindamage was moving string.maketrans to bytes):
import re
def main(words):
for word in words:
word = word.strip().upper()
if re.compile(r'[A-FOI]{6}$').match(word):
print('#' + word.replace('I', '1').replace('O', '0'))
if __name__ == '__main__':
main(open('/usr/share/dict/words'))
I think the shell version is clearly better for interactive improvisation, though.
- js2 4y agoI prefer search with an explicit '^' in the pattern to using match. For a throw-away script I'd probably do this: import re is_hex_like = re.compile(r"^[a-foi]{6}$", re.I).search for word in filter(is_hex_like, open("/usr/share/dict/words")): hexword = word.upper().replace("O", "0").replace("I", "1").rstrip() print(f"#{hexword}")
- kragen 4y agoThat's nicer than my version! I'm curious why you prefer search(), though.
- js2 4y ago1. I don't have to remember which implicitly anchors to the start of the string and which doesn't. 2. I prefer the explicitness of '^' (maybe that's just another way of stating (1). 3. I can use re.M to modify '^' to match at the start of each line on multiline strings, whereas match will still keep searching from the front. 4. The asymmetry of anchoring the front but not the end is weird. Python now has fullmatch, but ugh, just use the pattern for that if you need it. 5. Off the top of my head, I can't think of another language that has a regex function that implicitly anchors the front.
- kragen 4y agoHmm, I see. Interesting! I think of regexps as state machines, so I think of the implicit loop to find a starting position as extra complexity, which can give rise to for example performance problems, though it's true that in many languages you can't avoid it.
- Too 4y agofindall and multiline mode makes it even easier, at the cost of loading whole file into memory though, for that reason your alternaive is probably better import re wordlist = open("/usr/share/dict/words").read() for word in re.findall(r"^[a-foi]{6}$", wordlist, re.IGNORECASE | re.MULTILINE): hexword = word.upper().replace("O", "0").replace("I", "1") print(f"#{hexword}")