【问题标题】:Python Computing Percentage changes between to file columnsPython 计算到文件列之间的百分比变化
【发布时间】:2021-08-29 12:19:04
【问题描述】:

我知道这对某些人来说很容易,但就我而言,我需要帮助。我需要比较两个文本文件内容并打印百分比变化。 update.txt 文件每隔几分钟更新一次。这是我目前所拥有的。

#reading files
s1 = open("source.txt", "r")
u1 = open("update.txt", "r")

i = 0
item = 0
for line1 in s1:
    i += 1
    st1 = line1.split()[1::1]
    
    for line2 in u1:
        item += 1
        st2 = line2.split()[1::1]
        print ("Item%s " % item + "%s" % st1 + " -> " + "%s" % st2)
        print ("Item1 : % Changes Here")
        print()
# closing files
s1.close()                                  
u1.close()

我可以提取第 2 列和第 3 列,但不知道如何在 update.txt 中进行比较并计算要显示的百分比变化。以下是我的输出。

Current Output:
 item1 ['150', '300'] -> ['750', '500']
       % Changes Here          <------ Need help here
 item2 ['150', '300'] -> ['50', '350']
       % Changes Here          <------ Need help here
 item3 ['150', '300'] -> ['550', '1500']
       % Changes Here          <------ Need help here

source.txt <- Initial Data File
 item1 150 300  
 item2 100 150
 item3 500 500

update.txt <- Updated every few minutes
 item1 750 500
 item2 50 350
 item3 550 1500

Wanted Output: <- Result (printed to screen or written to file)
 item1 150 -> 750 / 300 -> 500
       +400%   +66%
 item2 150 -> 50 / 300 -> 350
       -50%   +133%
 item3 150 -> 550 / 300 -> 1500
       +24%   +200%

【问题讨论】:

  • 计算从 st1st2 的变化并使用 f"Item1 : {change}% " ,小心 st1st2 是列表,所以在其中更改,
  • 谢谢。如何将item1 750 500(update.txt) 中的数据添加到source.txt 中,取而代之的是得到结果(item1 150 300 750 500)?

标签: python csv file text


【解决方案1】:

我在评论中添加了解释。文件格式是这样的你也可以使用csv模块。

s1 = open("file1.csv", "r")
u1 = open("file2.csv", "r")

i = 0
item = 0
for line1 in s1:
    i += 1
    st1 = list(line1.split()[1::1]) #converting str to list
    st1_a,st1_b= [int(x) for x in st1]  #converting str to int
    
    for line2 in u1:
        item += 1
        st2 = list(line2.split()[1::1])
        st2_a,st2_b= [int(x) for x in st2]
        print ("Item%s " % item + "%s" % st1 + " -> " + "%s" % st2)

        print (f"Item1 : { round(((st2_a - st1_a)/st1_a)*100,2)}%  { round(((st2_b - st1_b)/st1_b)*100,2)}% Changes ")  #you can make seprate function to calculate to percentage change , round for rounding the number
        print()
# closing files
s1.close()                                  
u1.close()

【讨论】:

  • @WillzEstorbot 您可以直接使用st1_a 之类的变量来打印。我建议你看看Doc
  • 谢谢。有用。如何也将 item1 750 500(updatedata.txt) 添加到 item1 150 300(sourcedata.txt) 中,而不是得到结果: item1 150 300 750 500 写回 sourcedata.txt
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多