【问题标题】:hello,PLease help me with txt.in Python你好,请帮助我使用 txt.in Python
【发布时间】:2021-01-19 19:58:26
【问题描述】:

必须在 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 这一定是结果

【问题讨论】:

  • 你能发一个expresii.txt的例子吗?
  • 您必须将两个数字 l[0]l[1] 存储在类似列表的列表中(存储数字及其结果),然后您可以遍历该列表并施展魔法使用字符串连接。

标签: python numbers subtraction txt


【解决方案1】:

这是一个 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 的过程中一切顺利:)

【讨论】:

  • 非常感谢你,你救了我的命,
  • @DoCreed 不用担心,祝你好运。如果您不理解我的解决方案的任何部分,请务必询问!
  • 我知道你是怎么做到的,要理解这一切还有很长的路要走,我最大的问题是 python 中的求和,似乎无法完全理解它是如何工作的。
  • @DoCreed by sum,你是指用于迭代的 sum() 函数,还是只是加法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
相关资源
最近更新 更多