[英]Find sum of numbers in line
這是我必須做的:
讀取文本文件的內容,其中每行有兩個以逗號分隔的數字(如10, 5\\n
, 12, 8\\n
, ...)
對這兩個數字求和
將兩個原始數字寫入新的文本文件,求和結果 = 像10 + 5 = 15\\n
, 12 + 8 = 20\\n
, ...
到目前為止,我有這個:
import os
import sys
relative_path = "Homework 2.txt"
if not os.path.exists(relative_path):
print "not found"
sys.exit()
read_file = open(relative_path, "r")
lines = read_file.readlines()
read_file.close()
print lines
path_output = "data_result4.txt"
write_file = open(path_output, "w")
for line in lines:
line_array = line.split()
print line_array
讓你的最后一個for
循環看起來像這樣:
for line in lines:
splitline = line.strip().split(",")
summation = sum(map(int, splitline))
write_file.write(" + ".join(splitline) + " = " + str(summation) + "\n")
這種方式的一個美妙之處在於,您可以在一行中包含任意數量的數字,並且它仍然可以正確顯示。
你需要對python有很好的理解才能理解這一點。
首先,讀取文件,並通過用換行符( \\n
)拆分來獲取所有行
對於每個表達式,計算答案並寫出來。 請記住,您需要將數字轉換為整數,以便將它們相加。
with open('Original.txt') as f:
lines = f.read().split('\n')
with open('answers.txt', 'w+') as f:
for expression in lines: # expression should be in format '12, 8'
nums = [int(i) for i in expression.split(', ')]
f.write('{} + {} = {}\n'.format(nums[0], nums[1], nums[0] + nums[1]))
# That should write '12 + 8 = 20\n'
似乎輸入文件是 csv 所以只需在 python 中使用 csv reader 模塊。
輸入文件作業2.txt
1, 2
1,3
1,5
10,6
劇本
import csv
f = open('Homework 2.txt', 'rb')
reader = csv.reader(f)
result = []
for line in list(reader):
nums = [int(i) for i in line]
result.append(["%(a)s + %(b)s = %(c)s" % {'a' : nums[0], 'b' : nums[1], 'c' : nums[0] + nums[1] }])
f = open('Homework 2 Output.txt', 'wb')
writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for line in result:
writer.writerow(line)
輸出文件則是 Homework 2 Output.txt
1 + 2 = 3
1 + 3 = 4
1 + 5 = 6
10 + 6 = 16
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.