【发布时间】:2021-02-10 01:46:29
【问题描述】:
我的目标是将文本文件中的行打印在一起。然而,有些行并没有像他们应该的那样在一起。我解决了分母在后面的第一个问题。对于else 语句,它们似乎都具有相同的值/索引。
import fitz # this is pymupdf
with fitz.open("math-problems.pdf") as doc: #below converts pdf to txt
text = ""
for page in doc:
text += page.getText()
file_w = open("output.txt", "w") #save as txt file
file_w.write(text)
file_w.close()
file_r = open("output.txt", "r") #read txt file
word = 'f(x) = '
#--------------------------
list1 = file_r.readlines() # read each line and put into list
list2 = [k for k in list1 if word in k] # look for all elements with "f(x)" and put all in new list
list1_N = list1
list2_N = list2
list1 = [e[3:] for e in list1] #remove first three characters (the first three characters are always "1) " or "A) "
char = str('\n')
for char in list2:
index = list1.index(char)
def digitcheck(s):
isdigit = str.isdigit
return any(map(isdigit,s))
xx = digitcheck(list1[index])
if xx:
print(list1[index] + " / " + list1_N[index+1])
else:
print(list1[index] + list1[index+1]) # PROBLEM IS HERE, HOW COME EACH VALUE IS SAME HERE?
终端输出:
f(x) = x3 + x2 - 20x
/ x2 - 3x - 18
f(x) =
2 + 5x
f(x) =
2 + 5x
f(x) =
2 + 5x
f(x) =
2 + 5x
f(x) = x2 + 3x - 10
/ x2 - 5x - 14
f(x) = x2 + 2x - 8
/ x2 - 3x - 10
f(x) = x - 1
/ x2 + 8
f(x) = 3x3 - 2x - 6
/ 8x3 - 7x + 4
f(x) =
2 + 5x
f(x) = x3 - 6x2 + 4x - 1
/ x2 + 8x
Process finished with exit code 0
【问题讨论】:
-
我认为问题出在
index = list1.index(char)中,无论char导致xx为假可能是在list2 中重复和/或始终相同的东西,所以当你在 list1 中询问它的索引,你当然会得到相同的结果 -
在不同的地方放一些打印和/或打印列表的内容,以便您找出问题...
-
@Copperfield 感谢您的评论。
xx产生真或假值以确定每个索引是否有整数。如果它有一个整数,它产生true,而如果它没有一个整数,它产生false。这些true值重复。却有不同的指标。false值重复并具有相同的索引。xx应该有重复的布尔运算符。 -
我猜这很有趣,但不是问题,就像我说的那样,我认为问题出在
char或更准确地说是在 list2 中,这可能看起来像['1',' ','2',' ','3']的效果因此,当您迭代它时,例如,当 char 为'1'时它可以正常工作,但是当 char 为' '并且您要求它的索引时,您会在另一个列表中第一次出现它,因此您总是得到相同的结果 -
@Copperfield 哦,我明白了。我对 Python 还很陌生,所以感谢您的帮助。我会看看这是否是
char的问题。谢谢。