【发布时间】:2015-11-04 22:05:12
【问题描述】:
一家巧克力公司决定为当前日期前 30 天以上生产的糖果产品提供折扣。我必须有一个矩阵作为打印结果,程序读取 2 个文件,一个是不同大小的不同糖果的成本,另一个是提供折扣的阈值天数。所以在这个问题中,两个文本文件看起来像这样
糖果.txt
31 32 19 11 15 30 35 37
12 34 39 45 66 78 12 7
76 32 8 2 3 5 18 32 48
99 102 3 46 88 22 25 21
fd zz er 23 44 56 77 99
44 33 22 55 er ee df 22
还有第二个文件days.txt
30
但它可以有多个数字。它可能看起来像
30
40
36
想要的输出是
Discount at days = 30
$ $ $
$ $ $
$ $ $ $ $
$ $ $ $
? ? ? $
$ ? ? ? $
Discount at days = 40
And then execute the output accordingly
所以基本上,只要数字低于 days.txt 中给出的数字,它就应该打印一个"$" 符号,而在任何超过数字(在我们的例子中为 30)的地方,它都应该在它们的位置打印空格。我们还有一个异常,我们在 candies.txt 矩阵中有英文字母,因为我们正在寻找数字来检查价格而不是字母,它应该在它们的位置打印一个 "?" 符号,因为它无法识别。
这是我的代码
def replace(word, threshold):
try:
value = int(word)
except ValueError:
return '?'
if value < threshold:
return '$'
if value > threshold:
return ' '
return word
def get_threshold(filename):
thresholds = []
with open(filename) as fobj:
for line in fobj:
if line.strip():
thresholds.append(int(line))
return thresholds
def process_file(data_file, threshold):
lines = []
print('Original data:')
with open(data_file) as f:
for line in f:
line = line.strip()
print(line)
replaced_line = ' '.join(
replace(chunck, threshold) for chunck in line.split())
lines.append(replaced_line)
print('\nData replaced with threshold', threshold)
for threshold in get_threshold('days.txt'):
process_file('demo.txt', threshold )
我的问题是,当第二个文件 days.txt 中只有一个数字时,我的代码有效,但当第二个文件中有多个数字时,我的代码无效。我希望它在第二个文本文件的每个换行符中有多个数字时工作。我不知道我做错了什么。
【问题讨论】:
-
当你在第二个文件中尝试使用多个数字时会发生什么?
-
我收到错误 `line = int(line) ValueError: invalid literal for int() with base 10: '104\n88\n99\n9988'``
-
当第二个文件中有多个数字时,您希望发生什么?它是否为每个数字生成一个序列?还是选择最高的?还是什么?
-
哦,它应该产生与数字一样多的输出
-
欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 MCVE 适用于此。在您发布代码并准确描述问题之前,我们无法有效地帮助您。在这种情况下,请特别包含问题运行的跟踪输出和完整错误(文本和堆栈跟踪)。
标签: python parsing python-3.x function