[英]Extract only numeric value from string within Python list
嗨,我想要做的是僅從某個列表項中的字符串中提取數字,但是結果用括號 [] 打印。 如何刪除它們? 我得到的結果是 [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))
那對你有用嗎? 您的原始印刷品做了一些可愛的額外工作,將所有結果放入一個列表中,但這似乎並不是您最終需要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.