python - 在两个字符串中查找被替换的单词

python - Find replaced words in two strings

我有两个字符串,比方说:

a = "Hello, I'm Daniel and 15 years old."
b = "Hello, I'm (name) and (age) years old."

现在我想 python 找到被替换的词。它可以是这样的:

{"name": "Daniel", "age": "15"}

我从来没有找到解决办法!非常感谢您的帮助!

您可以使用 zip() with str.split() 和字符串切片(从键中删除 ()):

res = {v[1:-1]: k for k, v in zip(a.split(), b.split()) if k !=v}

str.split() 用于在空格处拆分每个字符串。

输出:

>>> res
{'name': 'Daniel', 'age': '15'}

使用 python3 您可以使用字典中的值格式化字符串。

"Hello, I'm {name} and {age} years old.".format(**{"name": "Daniel", "age": "15"})

c = {"name": "Daniel", "age": "15"} "Hello, I'm {name} and {age} years old.".format(**c)

或者,如果您询问如何提取这些值,您可以使用正则表达式找到这些值:

import re
regularExpression = "^Hello, I'm (.*) and ([0-9]*).*"
input = "Hello, I'm Daniel and 15 years old."
match = re.search(regularExpression,input)
result = {"name": match.group(1), "age": match.group(2)}