1

必须在 python 2 txt.files 中写入一个是输入数字:在 2 行 4-1 和 12-3 中写入我必须进行减法并将结果写入其他 txt.file

请帮助我我对python很陌生,刚开始学习它。提前谢谢大家

这是我到现在为止写的:

    import calculator
    with open ('./expresii.txt', 'r') as f:
      line = f.readlines()
      for l in line:
        if l[1] == '-':
          print(calculator.subtraction(int(l[0]), int(l[2])))
        else:
          print(calculator.addition(int(l[0]), int(l[2])))

    with open ('./expresii.txt', 'r') as f2:
      print(f2.read())

首先我得到数字的减法,然后我得到必须减去的数字

现在我如何写入新文件 4-1=3 和 12-3=9 这一定是结果

4

1 回答 1

0

这是一个 Python 2.7 解决方案:

import re
# opens the input file in readmode
with open ('expresii.txt', 'r') as f:
    # creates an iterable of the lines in the file
    lines = f.readlines()
    # create an empty array which will store the data to write to the output file
    to_file = []
    # loops through every line in the file
    for l in lines:
        # creates a list of ints of all the numbers in that line
        nums = list(map(int, re.findall(r'\d+', l)))
        # calculate the result by subtracting the two numbers
        result = nums[0] - nums[1]
        # append answer (e.g 4-1=3) to a list, that will later be written to a file
        line = str(nums[0])+'-'+str(nums[1])+'='+str(result)+'\n'
        to_file.append(line)

#open the output file in write mode
with open('output_file.txt', 'w') as f:
    # write the to_file list to output_file.txt
    f.writelines(to_file)

此解决方案在文件的每一行中查找所有数字,并在减去它们时计算结果。在对输入文件中的每一行完成此操作后,它会将这些数据写入输出文件。

祝你在继续学习 Python 的过程中一切顺利 :)

于 2021-01-19T20:32:35.247 回答