首页 > 解决方案 > 正则表达式在 python 中规范化这些拼写

问题描述

我需要您的指导才能使此代码正常工作。当我运行它时,它会返回所有修改过的单词,但缺少某些部分。示例将 u 转换为 u,当 u 在以下单词 gouuernement、reuestu、gouuvernez 等词中的元音之前进入 v 时,它返回 vernement、vestu、vernez 而不是 gouvernement、revestu、gouvernez ....也在 re.compile 方法中我会喜欢包含修改不涉及的单词列表。亲爱的用户,请新手需要您的帮助来解决正则表达式中的问题。

import re, string, unicodedata
import spacy
import codecs
import io
nlp = spacy.load('fr')
with codecs.open(r'/home/fatkab/RD/rule6output.txt', encoding='utf8')as f6:
  word6 =f6.read()
sub_pattern6= re.compile(r"\b[a-zA-Z]+[aieuo]+u([aieuo]+[a-zA-Z]+\b)")#turn u to v in words such as seruitude, gouuernement ,renouueller ...
print(re.sub(sub_pattern6, r"v\1", word6))

标签: python-3.x

解决方案


如果您的意图只是用另一个字符(此处为 'v')替换一个字符(此处为 'u'),那么您可以通过以下方式进行:

with open('path/to/your/file.txt', 'r+') as f:
    file_str = f.read()
    print(file_str)
    file_str = file_str.replace('u','v') # replacing the file str
    print(file_str) # later you can write this variable to the file itself

希望有帮助。


推荐阅读