arrays - 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?
解决方案
使用正则表达式检查单词是否以非元音结尾并不难,但在这种情况下,您不会替换,但如果您有匹配项,请在单词中添加一个字母。
将检查给定字符串末尾是否存在元音的正则表达式是
[^aeiou]{1}$
然后在python中我想做类似的事情
regexp = re.compile(r'[^aeiou]{1}$')
if regexp.search(word):
word += 'x'
# do more stuff
我会彻底检查以执行此操作的方式构建的 python 是否不是更快。
推荐阅读
- mongodb - 使用 $addFields 将子属性添加到 Mongo 文档的根目录
- c++ - 是否可以将继承的类成员声明为私有?
- angular - Run function when tab is selected - Angular2+NativeScript
- python - 使用 Tkinter 图像的问题
- python - 从用户界面删除 csv 文件中的列表项
- laravel - Laravel 方法 [index@index] 不存在
- python - Gunicorn3 不是从 systemd 开始的
- laravel - Laravel 同步作业 - 如何停止/刷新
- git - 如何将文件两个不同的文件添加到两个不同的存储库中?
- ios - Swift shapeLayer.fillColor 在单元格内容视图中不起作用