簡體   English   中英

Python:解析包含字符串,整數和逗號的混合文本輸入文件

[英]Python: parsing a text input file containing a mix of strings, integers and commas

我是python的新手,盡管我知道許多其他計算機語言。 問題是從格式為12行的文本文件中讀取數據:

一月(7,14,13,9)

從1月到12月,每行一個月(每個周期有4個整數),因此可以對數據中的整數執行計算。

輸入數據中的括號讓我感到困惑,是否有一種有效的方法可以從數據文件中提取整數? 我最終可以自己解決這個問題,但是我正在嘗試幫助其他人,這是有時間因素的。 提前致謝。

您可以使用抽象語法樹來獲取值的元組

>>> import ast
>>> line = 'Jan(7, 14, 13, 9)'
>>> j = line.index('(')
>>> line[:j]  # month
'Jan'
>>> ast.literal_eval(line[j:]) # a tuple of values
(7, 14, 13, 9)

希望這可以幫助:

>>> s = 'Jan(7, 14, 13, 9)'
>>> idx = s.index('(') #find the index of (
>>> idx
3
>>> s[idx+1:-1] #the content of ()
'7, 14, 13, 9'
>>> list(int(x) for x in s[idx+1:-1].split(',')) #now a split and a list comprehension
[7, 14, 13, 9]
>>> 

如您所說,假設線條具有圖案。

line = 'Jan(7, 14, 13, 9)'

parsed_line = eval(line[3::])

sum_all = sum(parsed_line)
>>> 43 

它返回一個元組。

暫無
暫無

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

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