python - 我想在 python 中遍历一个 txt 并更改每个单词
问题描述
我有一个名为的结构dictionary
,它看起来像这样:
dictionary = {"The" : "A", "sun": "nap", "shining" : "süt",
"wind": "szél", "not" : "nem", "blowing" : "fúj"}
我想遍历 .txt 并将每个单词更改为其密钥对并将其推送到新的 txt。
我的想法是这样的,但它只是返回值:
dict = {"The" : "A", "sun": "nap", "shining" : "süt", "wind" : "szél", "not" : "nem", "blowing" : "fúj"}
def translate(string, dict):
for key in dict:
string = string.replace(key, dict[key]())
return string()
解决方案
用于re
避免重叠替换。该模式是从转义键构建的,替换字符串使用 lambda 表达式动态映射。
import re
table = {"The": "A", "sun": "nap", "shining": "süt", "wind": "szél", "not": "nem", "blowing": "fúj"}
def translate(string, mapping):
pattern = r'(' + r'|'.join(re.escape(k) for k in mapping.keys()) + r')'
return re.sub(pattern, lambda m: mapping[m.group(1)], string)
print(translate('The sun is not blowing wizd', table))
推荐阅读
- openstack-keystone - devstack - 如何减少 openstack keystone X-Subject-Token 大小
- c++ - 错误:''无法将'uint8* {aka unsigned int*}'转换为'const emxArray_uint8_T*'?'?
- asynchronous - 将独立的自动化作业与詹金斯管道集成
- google-chrome - captive.apple.com/generate_204 来自 Windows 10 的点击
- javascript - 如何从 MySQL 获取 RowDataPacket 对象?
- reactjs - 如何在不指定道具的情况下将数据传递给孩子
- sas - 在SAS中使用变量名在其他表上添加表
- db2 - DB2如何从两个表中获取多行的不喜欢
- maven - 通过命令行从 Maven 项目(由 Eclipse 开发)运行单个 JUnit 测试套件的问题(可能是错误的搜索路径)
- ruby-on-rails - 使用 turbolink 加载数据表