【问题标题】:How to replace code easily ? From VBA to Python如何轻松替换代码?从 VBA 到 Python
【发布时间】:2021-12-03 22:51:13
【问题描述】:

我在 VBA 中有 1300 行代码,它们看起来像这样:

ElseIf InStr(LCase(A), LCase("B")) Then function = "* C"

我想在 Python 中有这样的东西:

elif (df2["A"]=="B") is True:
        return "* C" 

只有A,B和C改变,你知道有什么办法吗?我的第一个想法是使用 print 和 .format 来做这样的事情:

print("elif (df2['{}']=='{}') is True: return '{}' ".format(A, "B", "* C"))
                   

但这对修改数百行是行不通的

【问题讨论】:

  • 您的代码似乎需要重构:1300 行代码很臭。
  • 你可能是对的,但如果条件变量信息和我真的不知道如何重构,所以它很复杂

标签: python dataframe if-statement converters


【解决方案1】:

如果有一天有人想知道。我毫不怀疑它存在更好的方法,但至少它有效:

import re
import csv
a = " "
compteur = 0
second_compteur, first_compteur = "", ""

with open(r"patch") as csvfile:
    liste1 = []
    for row in csvfile:
        a += row

        b = re.compile('"[^"]*"')

        for value in b.findall(a):
            if compteur % 2 == 0:
                first_compteur = value
            else:
                second_compteur = value
            compteur += 1

        with open(r"path_new_csv", "a", newline="") as csvfile2:
            writer = csv.writer(csvfile2, quotechar="'")
            writer.writerow(["elif (df2[{}]=={}) is True: return {}".format("ShortDescr", first_compteur, second_compteur)])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2013-08-15
    • 2011-01-12
    • 1970-01-01
    • 2013-08-30
    • 2012-11-03
    • 1970-01-01
    相关资源
    最近更新 更多