字转换

2024-05-14 03:17:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何将原诗转换成已转换的诗

它应该将cubits转换为feet

原诗:

"So make yourself an ark of cypress wood; make rooms in it and coat it with pitch inside and out. This is how you are to build it: The ark is to be 300 cubits long, 50 cubits wide and 30 cubits high. (Genesis 6:14-15)"

转换诗:

"So make yourself an ark of cypress wood; make rooms in it and coat it with pitch inside and out. This is how you are to build it: The ark is to be 450 feet long, 75 feet wide and 45 feet high. (Genesis 6:14-15)"


Tags: andoftoanmakesoisit
2条回答

记下每个单词,然后检查值

差不多

conversion_factor = 1.5
words = verse.split()
for i, word in enumerate(words):
    if i < len(words)-1 and words[i+1] == 'cubits':
        amount = int(word)
        word = int(amount * conversion_factor)
    if word == 'cubits':
        word = 'feet'
    print(word, end = ' ')

输出

"So make yourself an ark of cypress wood; make rooms in it and coat it with pitch inside and out. This is how you are to build it: The ark is to be 450 feet long, 75 feet wide and 45 feet high. (Genesis 6:14-15)"

您可以匹配正则表达式,并使用替换函数调整单位(并更改单位名称)

import re

r = re.compile("(\d+) cubits")

s = "So make yourself an ark of cypress wood; make rooms in it and coat it with pitch inside and out. This is how you are to build it: The ark is to be 300 cubits long, 50 cubits wide and 30 cubits high. (Genesis 6:14-15)"

print(r.sub(lambda m : "{} feet".format(int(float(m.group(1))*1.5)),s))

结果:

So make yourself an ark of cypress wood; make rooms in it and coat it with pitch inside and out. This is how you are to build it: The ark is to be 450 feet long, 75 feet wide and 45 feet high. (Genesis 6:14-15)

当正则表达式匹配后跟“cubits”的数字时,它调用lambda回调,解析该数字,乘以1.5,转换回整数,并用新的单位重新格式化输出

这将不得不微调为1英尺,并可以使用转换字典,如果有更多的单位转换

相关问题 更多 >