首页 > 解决方案 > Array of strings with re

问题描述

This answer suggested me a code for having an array of conditions for replacements. Now I want to have one more condition which cannot be coded in the same way.

kxyz
sxyz
pxyz
clxyz
bookabcd
lookabcd
cookabcd
packabcd
bank
lab
court
catch

This is the updated word list

import re

# List where first is pattern and second is replacement string
replacements = [("ing$", "xyz"), ("ed$", "abcd")]

with open("new_abcd.txt", "w") as new, open("abcd.txt") as original:
    for word in original:
      new_word = word
      for pattern, replacement in replacements:
        new_word = re.sub(pattern, replacement, word)
        if new_word != word:
           break
      new.write(new_word)

Let's say I want to code a conditions for words like 'bank', 'lab', 'court', 'catch' that says add "x". One may wonder what is a pattern in these words. It's nothing but all of these words are consonant ending. I don't know the Python way of doing this, but I want something like if the word does not end in ("a" or "e" or "i" or "o" or "u") change it to something else. Can re handle this?

标签: arrays

解决方案


使用正则表达式检查单词是否以非元音结尾并不难,但在这种情况下,您不会替换,但如果您有匹配项,请在单词中添加一个字母。

将检查给定字符串末尾是否存在元音的正则表达式是

[^aeiou]{1}$

然后在python中我想做类似的事情

regexp = re.compile(r'[^aeiou]{1}$') if regexp.search(word): word += 'x' # do more stuff

我会彻底检查以执行此操作的方式构建的 python 是否不是更快。


推荐阅读