本文介绍了比较两个字符串并在Python中提取变量数据的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的 python 脚本中,我有一个字符串列表,如
In my python script,I have a list of strings like,
birth_year = ["my birth year is *","i born in *","i was born in *"]
我想将一个输入句子与上面的列表进行比较,并且需要一个出生年份作为输出.
I want to compare one input sentence with the above list and need a birth year as output.
输入语句如下:
Example1: My birth year is 1994.
Example2: I born in 1995
输出将是:
Example1: 1994
Example2: 1995
我通过使用正则表达式应用了许多方法.但我没有找到完美的解决方案.
I applied many approaches by using regex. But I didn't find a perfect solution for the same.
推荐答案
如果将 birth_year
更改为正则表达式列表,则可以更轻松地与输入字符串匹配.使用年度捕获组.
If you change birth_year
to a list of regexes you could match more easily with your input string. Use a capturing group for the year.
这是一个可以执行您想要的操作的函数:
Here's a function that does what you want:
def match_year(birth_year, input):
for s in birth_year:
m = re.search(s, input, re.IGNORECASE)
if m:
output = f'{input[:m.start(0)]}{m[1]}'
print(output)
break
示例:
birth_year = ["my birth year is (\d{4})","i born in (\d{4})","i was born in (\d{4})"]
match_year(birth_year, "Example1: My birth year is 1994.")
match_year(birth_year, "Example2: I born in 1995")
输出:
Example1: 1994
Example2: 1995
对于 f 字符串,您至少需要 Python 3.6.
You need at least Python 3.6 for f-strings.
这篇关于比较两个字符串并在Python中提取变量数据的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!