【问题标题】:Python 3.7 else statement not showing correct index?Python 3.7 else 语句没有显示正确的索引?
【发布时间】: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 的问题。谢谢。

标签: python pymupdf


【解决方案1】:

已解决 @copperfield 是正确的,我有重复的值,所以我的索引是重复的。我使用@Shonu93 在here 中的解决方案解决了这个问题。本质上,它定位所有重复值的索引并将这些索引放入一个列表elem_pos,然后从list1打印每个索引

if empty in list1:
counter = 0
elem_pos = []
for i in list1:
    if i == empty:
        elem_pos.append(counter)
    counter = counter + 1
xy = elem_pos

for i in xy:
print(list1[i] + list1_N[i+1])

【讨论】:

    猜你喜欢
    • 2023-02-09
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    相关资源
    最近更新 更多