[英]How to make a list of integers that is the sum of all the integers from a set of lists in a dict?
[英]How to make lists of integers from a portion of a file with Python?
我有一個如下文件 :
@ junk
...
@ junk
1.0 -100.102487081243
1.1 -100.102497023421
... ...
3.0 -100.102473082342
&
@ junk
...
我只對@
和&
字符之間的兩列數字感興趣。 這些字符可能會出現在文件中的其他任何位置,但永遠不會出現在數字塊中。
我想創建兩個列表 ,一個帶有第一列,一個帶有第二列。
List1 = [1.0, 1.1,..., 3.0]
List2 = [-100.102487081243, -100.102497023421,..., -100.102473082342]
我一直在使用Shell腳本來為這些文件准備一個更簡單的Python腳本,以創建列表,但是,我正在嘗試將這些過程遷移到Python上以實現更一致的應用程序。 有任何想法嗎? 我對Python和文件處理的經驗有限。
編輯:我應該提到,此數字塊出現在文件中的兩個位置。 兩個數字塊是相同的。
Edit2:通用函數對此最為滿意,因為我將其放入自定義庫中。
目前的努力
我目前使用shell腳本將數字塊以外的所有內容修剪成兩列。 從那里開始,使用以下功能對我來說是微不足道的
def ReadLL(infile):
List = open(infile).read().splitlines()
intL = [int(i) for i in List]
return intL
通過我的主叫聲
import sys
import eLIBc
infile = sys.argv[1]
sList = eLIBc.ReadLL(infile)
問題是知道如何使用Python而不是使用Shell腳本從原始文件中提取數字塊。
您想遍歷文件本身,並為找到沒有 @
字符的第一行設置一個標志,此后可以開始收集數字。 在一行上找到&
字符時,請中斷閱讀。
def readll(infile):
with open(infile) as data:
floatlist1, floatlist2 = [], []
reading = False
for line in data:
if not reading:
if '@' not in line:
reading = True
else:
continue
if '&' in line:
return floatlist1, floatlist2
numbers = map(float, line.split())
floatlist1.append(numbers[0])
floatlist2.append(numbers[1])
所以上面:
False
,並且僅當找到沒有'@'
的行時才將其設置為True
。 True
:
&
則返回讀取的數據 通過返回,該函數結束,文件自動關閉。 僅讀取第一個塊,而忽略文件的其余部分。
試試看:
with open("i.txt") as fp:
lines = fp.readlines()
data = False
List1 = []
List2 = []
for line in lines:
if line[0] not in ['&', '@']:
print line
line = line.split()
List1.append(line[0])
List2.append(line[1])
data = True
elif data == True:
break
print List1
print List2
這應該給您第一組數字。
輸入:
@ junk
@ junk
1.0 -100.102487081243
1.1 -100.102497023421
3.0 -100.102473082342
&
@ junk
1.0 -100.102487081243
1.1 -100.102497023421
輸出:
['1.0', '1.1', '3.0']
['-100.102487081243', '-100.102497023421', '-100.102473082342']
更新資料
如果您需要兩個塊,請使用以下命令:
with open("i.txt") as fp:
lines = fp.readlines()
List1 = []
List2 = []
for line in lines:
if line[0] not in ['&', '@']:
print line
line = line.split()
List1.append(line[0])
List2.append(line[1])
print List1
print List2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.