仅从Python列表中的字符串中提取数值

仅从Python列表中的字符串中提取数值,python,Python,嗨,我想做的是从特定列表项中的字符串中只提取数字,但结果是用括号[]打印的。如何移除它们? 我得到的结果是[2000],而不是2000 #!/usr/bin/env python # -*- coding: utf-8 -*- #opening txt file to extract data import io with io.open("testmodi.txt", "r", encoding="cp1250") as file: ocr_results = [line.str

嗨,我想做的是从特定列表项中的字符串中只提取数字,但结果是用括号[]打印的。如何移除它们? 我得到的结果是[2000],而不是2000

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#opening txt file to extract data
import io

with io.open("testmodi.txt", "r", encoding="cp1250") as file:
     ocr_results = [line.strip() for line in file]

#spliting into list     
for line in ocr_results:
    print("[" + line + "]")



class overeview_mth:
 def __init__(self):
    self.closest_string = "Opis"
    self.distance_between_closest_string_and_matching_index = + 1
    self.every_matching_index_list_within_ocr_results = [i for i, x in enumerate(ocr_results) if x == self.closest_string]
    self.number_of_string_occurence_within_ocr_results = len(self.every_matching_index_list_within_ocr_results)
    self.matching_index = int(self.every_matching_index_list_within_ocr_results[self.number_of_string_occurence_within_ocr_results -1] + self.distance_between_closest_string_and_matching_index)



#for testing
target_index = overeview_mth()

print([int(s) for s in ocr_results[(target_index.matching_index)].split() if s.isdigit()])

如果您希望单独打印每个列表值,则需要按照Juanpa的建议将它们从列表中删除。代码应该是这样的,从您的代码改编:

for s in ocr_results[(target_index.matching_index)].split():
    if s.isdigit:
        print (int(s))

这对你有用吗?您原来的打印做了一些可爱的额外工作,将所有结果放入一个列表,但这似乎不是您最终需要的。

您正在打印一个列表,那么您希望得到什么?也许只是索引一下吧?是的,谢谢,就这样!。我不是一个程序员,只是一个简单的工作程序。