【问题标题】:Parsing text files to a matrix using python使用python将文本文件解析为矩阵
【发布时间】:2015-10-29 22:00:57
【问题描述】:

一家巧克力公司决定为当前日期前 30 天以上生产的糖果产品提供折扣。我必须有一个矩阵作为打印结果,程序读取 2 个文件,一个是不同大小的不同糖果的成本,另一个是提供折扣的阈值天数。 所以基本上,在数字低于 30 的任何地方(这是 days.txt 的输入)它应该打印一个 "$" 符号,并且在任何超过数字的地方(在我们的例子中为 30)它应该只在它们的位置打印空格。我们还有一个异常,我们在 candies.txt 矩阵中有英文字母,因为我们正在寻找数字来检查价格而不是字母,它应该在它们的位置打印一个 "?" 符号,因为它无法识别。

这就是我想要做的。

candy = []
with open('demo.txt', 'r') as f:
    for line in f:
        line = line.strip()
    if len(line) > 0:
        candy.append(map(int, line.split()))
print(candy, end='')

parsedList=[]
with open("demo.txt","r") as f:
    lst=f.read().splitlines()
    for i in lst:
        parsedList.append(i.split())
with open("days.txt","r") as f:
    param = int(f.readline().split("=")[1])

for innerList in parsedList:
    for element in innerList:
        if element.isdigit():
            if int(element)>=param:
                print (" ", end='')
            else:
                print( "$", end='')
        else:
            print ("?", end='')
    print(string, end='')

我的问题是我正在尝试打印文件 demo.txt,然后让 python 以矩阵形式打印带有替换值的输出。我的值正在打印,但它们不在矩阵中,也没有打印第一个文本文件。

【问题讨论】:

  • 你的第一个 if 语句没有正确缩进。你是什​​么意思我的“我的价值观正在打印但它们不在矩阵中”?如果您的意思是所有内容都作为新行打印,请使用print(string, end='') 避免新行
  • 我编辑了一些。不知道你打算如何停止新行
  • 您的输入文件格式似乎不同,您使用逗号 (,) 进行拆分
  • 很抱歉。我正在做另一个有逗号的文件,忘记删除它们。我现在已经编辑了。
  • 不,我的意思是替换您当前的所有打印功能并添加end='' 令牌。不要替换您所做的那个,那个是必要的,因为您确实希望每个文件都有一个换行符。不管怎样,@LetzerWille 发布了一个非常好的答案

标签: python function parsing python-3.x matrix


【解决方案1】:
def repl(ch,threshold):
    if ch.isdigit():
        if int(ch) < threshold:
            return '$'
        elif int(ch)> threshold:
            return " "
        else:
            return ch
    else:
        return '?'
lines = []
with open('data') as f, open("data.txt","r") as f2:
    threshold = int(f2.read().split('=')[-1])
    for line in f:
        line = line.strip()
        line = line.split()
        line = [repl(ch,threshold) for ch in line]
        lines.append(line)
    # reset to start of demo.txt
    f.seek(0)
    for line in f:
        print(line)

for line in lines:
    print()
    for el in line:
        print(el,end=" ")

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

    $ $ $ 30     
$           $ $ 
    $ $ $ $ $     
    $     $ $ $ 
? ? ? $         
    $   ? ? ? $ 

【讨论】:

  • 我们需要使用这两个文本文件并从中解析数据。不能硬编码。
  • @StarryNight 好的。在 days.txt 中将是一个日期列表,或者它是一个元组,我的意思是:Discount at days = [30,29,21...] or (30,28,32) ?
  • 在 days.txt 中,和我上面展示的完全一样。就像 Discount at days = 30 。现在值可以从 30 开始变化,它可以是任何值,但我们必须同时使用 demo.txt 和 days.txt 作为我们的数据。
  • @StarryNight 好的。看一看。现在将使用 days.txt
  • 但我们还必须在存在矩阵值的地方使用 demo.txt。