我有以下文本文件:
8/1 text1 1/5 text2 9/2
4/9 text1 3/1 text2 9/2
我想将所有分数转换为小数,但要保留格式和未转换的文本,所以转换后:
9.0 text1 1.2 text2 5.5
1.44 text1 4.0 text2 5.5
我可以使用下面的代码将分数转换为小数,但我不知道如何维护格式和未转换的文本:
import os
import re
from fractions import Fraction
import fileinput
import sys
def main():
text = open('text.txt').read()
regex = re.findall("\d/\d", text)
for dec_odd in regex:
dec_odd = Fraction(dec_odd)
dec_odd = float(dec_odd)
dec_odd = dec_odd +1
print(dec_odd)
if __name__ == "__main__":
main()
我试图遍历每行并一次转换一次,但又努力只转换分数而不是整行(以及类型的混合):
for line in fileinput.input("text.txt", inplace = 1):
frac_odd = re.search("\d/\d", line)
dec_odd = Fraction(frac_odd)
dec_odd = float(dec_odd)
print(line.replace(frac_odd, dec_odd))
答案 0 :(得分:3)
您可以使用re.sub()
:
import re
data = '''8/1 text1 1/5 text2 9/2
4/9 text1 3/1 text2 9/2'''
def format_fraction(a, b):
s = '{:.3g}'.format(float(a) / float(b) + 1)
if '.' not in s:
return s + '.0'
return s
s = re.sub(r'\b(\d+)/(\d+)\b', lambda g: format_fraction(g.group(1), g.group(2)) , data)
print(s)
打印:
9.0 text1 1.2 text2 5.5
1.44 text1 4.0 text2 5.5
答案 1 :(得分:1)
我相信您的做法正确,但是re.search()
不会返回str
,它会返回一个 match对象,您需要从中提取{{1 }}您想要的:
str
输出
import re
from fractions import Fraction
text = open('text.txt').read()
fraction = re.search(r"\d+/\d+", text)
while fraction:
string = fraction.group(0)
decimal = format(1.0 + float(Fraction(string)), '.3')
text = text.replace(string, decimal)
fraction = re.search(r"\d+/\d+", text)
print(text, end='')