我是编程新手,我需要完成我的一项任务。 (不要求解决方案)。我很困惑如何解决这个问题。如果您可以提供伪代码以使我朝正确的方向发展,那将会很有帮助。
到目前为止,
有关文本文件和相应的预期输出,请参考Text File。
例如:不使用镜头功能
x = input(“输入要读取的文件:”) y = input(“输入要写入的文件:”)
filereading = x.readline()
我需要去除哪些字符才能获得要添加的两个值。另外,我还需要输出在$#之间插入一个空格。
用于文件读取中的行: \ logic
答案 0 :(得分:1)
伪代码
open file as test_file
read test_file into something
split something to make list out of something
loop through something
remove $ from all items in something
open other_file to write to
create loop to sum 2 consecutive items in something
create variable to hold total of two items
write output statement to other_file
试图写出一个我如何用语言处理它的想法,以帮助您,下面是答案,同样不是让您跳过,而是在遇到困难时用作指导。
...
...
...
...
SPOILER:解决方案
test_file = open('money.txt', 'r')
content = test_file.read()
content = content.split()
for i in range(len(content)):
content[i] = content[i].strip('$')
other_file = open('print.txt', 'w')
for i in range(0, len(content), 2):
total = float(content[i]) + float(content[i+1])
other_file.write(f"${content[i]} + ${content[i+1]} = ${total}\n")
test_file.close()
other_file.close()
其他
with open(other_file, 'w') as f_obj:
total = float(content[0]) + float(content[1])
f_obj.write("$ " + content[0] + " $ " + content[1] + " $ " +
str(total) + "\n")
total = float(content[2]) + float(content[3])
f_obj.write("$ " + content[2] + " $ " + content[3] + " $ " +
str(total) + "\n")
total = float(content[4]) + float(content[5])
f_obj.write("$ " + content[4] + " $ " + content[5] + " $ " +
str(total) + "\n")
这是一个有关如何手动输入每个语句的示例,还请注意,如果像本示例一样使用with open
,则close
代码完成后文件应该with open
>