我正在尝试将每个打开的文本放入变量。
files_list = ["N1.txt", "N2.txt", "N3.txt", "N4.txt", "O1.txt", "O2.txt", "O3.txt", "O4.txt"]
j = 1
i = 0
num = len(files_list)
while i < num:
for file in files_list:
opentxt = open(files_list[i])
tovariable = opentxt + str(j)
i += 1
j += 1
我知道“tovariable”行不正确.. 我想要该变量来打开每个文本文件并将其放入变量“varj”。 我是python的新手,我正在努力实现工作中的自动化。
更新
让它发挥作用。也许这将有助于像我这样的人。
import xlwings as xw
def create_txt(h, ch):
for txt in range(h):
open("../check_results/{}{}.txt".format(ch, txt), "w")
try:
create_txt(4,ch = "N")
create_txt(4,ch = "O")
except:
input("ERROR - check_results folder was not found! \n\n Please create a folder with the name > check_results and try again\n\n\n")
exit()
new_text = ['N0.txt', 'N1.txt', 'N2.txt', 'N3.txt']
old_text = ['O0.txt', 'O1.txt', 'O2.txt', 'O3.txt']
def compare_txt(k, m):
match = []
new_text_match = []
old_text_match = []
new_i = []
old_i = []
for i in range(k):
n = open("../check_results/{}".format(new_text[i]), 'r').read().splitlines()
o = open("../check_results/{}".format(old_text[i]), 'r').read().splitlines()
n = " ".join(n).split()
o = " ".join(o).split()
j = 0
for nword in n:
for oword in o:
if nword == nword.upper() and oword == oword.upper():
j += 4
elif nword[0] == nword.upper()[0] and oword[0] == nword.upper()[0]:
j += 3
elif nword.lower() == oword.lower():
j += 1
try:
under_percent = ((len(n) + len(o)) / 2) / j
result = 100 / under_percent
if result > 100: result = 100
match.append("{}%".format(round(result, 2)))
new_text_match.append(" ".join(n))
new_i.append("{}".format(new_text[i]))
old_text_match.append(" ".join(o))
old_i.append("{}".format(old_text[i]))
print("Match found! Check: {} - {}".format(new_text[i], old_text[i]))
except:
print("No match found in {} - {}".format(new_text[i], old_text[i]))
nrow = []
orow = []
for nlist in new_text_match:
nseparate = "".join(nlist)
nrow.append(nseparate)
for olist in old_text_match:
oseparate = "".join(olist)
orow.append(oseparate)
try:
sht = xw.Book(r"../check_results/results.xlsx").sheets[m]
sht.clear_contents()
sht.range('A1').value = "It's a match!"
sht.range('A2').options(transpose=True).value = match
sht.range('B1').value = "Nx.txt"
sht.range('B2').options(transpose=True).value = new_i
sht.range('C1').value = "Text line from Nx.txt"
sht.range('C2').options(transpose=True).value = nrow
sht.range('D1').value = "Ox.txt"
sht.range('D2').options(transpose=True).value = old_i
sht.range('E1').value = "Text line from Ox.txt"
sht.range('E2').options(transpose=True).value = orow
except:
input("ERROR - results.xlsx file not found! \n Please create or paste results.xlsx in check_results folder.")
exit()
compare_txt(4, 0)
new_text = ['N0.txt', 'N0.txt', 'N3.txt']
old_text = ['O2.txt', 'O3.txt', 'O2.txt']
compare_txt(3, 1)
input("\n \n \n Analysis complete! \n Check results.xlsx file")