【问题标题】:Parsing two text files in Python for a combined result在 Python 中解析两个文本文件以获得组合结果
【发布时间】: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


【解决方案1】:

读取所有阈值:

def get_thresholds(filename):
    with open(filename) as fobj :
        return [int(line) for line in fobj if line.strip()]

没有列表理解的替代实现:

def get_thresholds(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 line in lines:
        print(line)

通过所有门槛:

for threshold in get_thresholds('days.txt'):
    process_file('candies.txt', threshold)

【讨论】:

  • 谢谢!但是在我们读取阈值的地方,我们不允许使用列表推导。
  • 使用循环添加了一个版本。
  • 好的,我按照您的建议编辑了我的代码(查看问题,我进行了编辑)但它仍然给我一个错误OSError: [Errno 9] Bad file descriptor
  • 您使用的是最新版本,即带有with open(filename) 的版本吗?
  • 是的,我是。您在问题中看到的代码就是我正在使用的代码。我用你的代码更新了它,但它仍然无法正常工作.....
【解决方案2】:

这是对我之前答案的重写。由于长时间的讨论和许多变化,另一个答案似乎更清楚。我将任务分成更小的子任务,并为每个子任务定义了一个函数。所有函数都有文档字符串。这是强烈推荐的。

"""
A chocolate company has decided to offer discount on the candy products
which are produced 30 days of more before the current date.

More story here ...
"""


def read_thresholds(filename):
    """Read values for thresholds from file.
    """
    thresholds = []
    with open(filename) as fobj:
        for line in fobj:
            if line.strip():
                thresholds.append(int(line))
    return thresholds


def read_costs(filename):
    """Read the cost from file.
    """
    lines = []
    with open(filename) as fobj:
        for line in fobj:
            lines.append(line.strip())
    return lines


def replace(word, threshold):
    """Replace value below threshold with `$`, above threshold with ` `,
       non-numbers with `?`, and keep the value if it equals the
       threshold.
    """
    try:
        value = int(word)
    except ValueError:
        return '?'
    if value < threshold:
        return '$'
    if value > threshold:
        return ' '
    return word


def process_costs(costs, threshold):
    """Replace the cost for given threshold and print results.
    """
    res = []
    for line in costs:
        replaced_line = '   '.join(
            replace(chunck, threshold) for chunck in line.split())
        res.append(replaced_line)

    print('\nData replaced with threshold', threshold)
    for line in res:
        print(line)


def show_orig(costs):
    """Show original costs.
    """
    print('Original data:')
    for line in costs:
        print(line)


def main(costs_filename, threshold_filename):
    """Replace costs for all thresholds and display results.
    """
    costs = read_costs(costs_filename)
    show_orig(costs)
    for threshold in read_thresholds(threshold_filename):
        process_costs(costs, threshold)


if __name__ == '__main__':
    main('candies.txt', 'days.txt')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多