簡體   English   中英

在python中讀取文件時如何讀取字符串作為整數

[英]How to read strings as integers when reading from a file in python

我在文本文件的特定部分中讀取了以下代碼行。 問題是這些數字不是字符串所以我想將它們轉換為int並將它們讀入某種列表。

文本文件中的數據樣本如下:

然而,這並不完全具有代表性我在這里上傳了完整的數據集: http//s000.tinyupload.com/?file_id = 08754130146692169643作為文本文件。

* NSET,NSET = Nodes_Pushed_Back_IB

99915527, 99915529, 99915530, 99915532, 99915533, 99915548, 99915549, 99915550, 99915551, 99915552, 99915553, 99915554, 99915555, 99915556, 99915557, 99915558, 99915562, 99915563, 99915564, 99915656, 99915657, 99915658, 99915659, 99915660, 99915661, 99915662, 99915663, 99915664, 99915665, 99915666, 99915667, 99915668, 99915669, 99915670, 99915885, 99915886, 99915887, 99915888, 99915889, 99915890, 99915891, 99915892, 99915893, 99915894, 99915895, 99915896, 99915897, 99915898, 99915899, 99915900, 99916042, 99916043, 99916044, 99916045, 99916046, 99916047, 99916048, 99916049, 99916050

* NSET,NSET = Nodes_Pushed_Back_OB

任何幫助將非常感激。

嗨,我仍然堅持這個問題更多的建議? 最新的代碼和錯誤信息如下謝謝!

 import tkinter as tk
 from tkinter import filedialog
 file_path = filedialog.askopenfilename()
 print(file_path)
 data =  []
 data2 = []
 data3 = []
 flag= False
 with open(file_path,'r') as f:
     for line in f:
         if line.strip().startswith('*NSET, NSET=Nodes_Pushed_Back_IB'):
             flag= True
         elif line.strip().endswith('*NSET, NSET=Nodes_Pushed_Back_OB'):
             flag= False    #loop stops when condition is false i.e if false do nothing
         elif flag:          # as long as flag is true append
             data.append([int(x) for x in line.strip().split(',')]) 

 result is the following error:

 ValueError: invalid literal for int() with base 10: ''

而不是將它們作為字符串讀取,我希望每個都是列表中的數字,即[98932850 98932852 98932853 98932855 98932856 98932871 98932872 98932873]

在這種情況下,我使用正則表達式和字符串方法。 我會像這樣解決這個問題:

import re 
with open(filepath) as f:
    txt = f.read()

g = re.search(r'NSET=Nodes_Pushed_Back_IB(.*)', txt, re.S)
snums = g.group(1).replace(',', ' ').split()
numbers = [int(num) for num in snums]

我把整個文本讀成了txt 接下來,我使用正則表達式並使用文本中標題的最后部分作為錨點,並使用捕獲括號捕獲所有其余部分(re.S標志表示點也應捕獲換行符)。 我通過g.group(1)所有nubers作為一個文本單元訪問。

下一個。 我刪除所有逗號(實際上用空格替換它們),因為在生成的文本中我使用split()這是一個很好的函數,用於用空格分隔的文本項 - 它與空格的數量無關,它只是像你想要的那樣分裂它。

其余的只是使用列表理解將文本轉換為數字。

您的行包含多個數字,以及一些分隔字符。 你可以通過明智地應用splitstrip來解析這種格式,或者你可以通過re提取你關心的字段來最小化字符串處理:

ints = list(map(int, re.findall(r'-?\d+', line)))

這個正則表達式將找到每組數字,可選地以減號為前綴,然后mapint應用於找到的每個這樣的組。

使用您的字符串示例:

strings = '  98932850,  98932852,  98932853,  98932855,  98932856,  98932871,  98932872,  98932873,\n'

我只是拆分字符串,刪除逗號,並返回一個數字列表:

numbers = [ int(s.strip(',')) for s in strings.split() ]

根據您的評論和您的代碼的更大背景。 我建議一些事情:

from itertools import groupby
number_groups = []
with open('data.txt', 'r') as f:
    for k, g in groupby(f, key=lambda x: x.startswith('*NSET')):
        if k:
            pass
        else:
            number_groups += list(filter('\n'.__ne__, list(g)))  #remove newlines in list

data = []
for group in number_groups:
    for str_num in group.strip('\n').split(','):
        data.append(int(str_num))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM