我想在一個目錄結構如下讀取不同的文件:讀取文件中的數據混合字符串和數字在python
# Mj = 1.60 ff = 7580.6 gg = 0.8325
我想讀每個文件和聯繫號碼每一個到向量。 如果我們假設我有3個文件,我將有3個向量Mj的組件,... 如何在Python中執行此操作?
感謝您的幫助。
我想在一個目錄結構如下讀取不同的文件:讀取文件中的數據混合字符串和數字在python
# Mj = 1.60 ff = 7580.6 gg = 0.8325
我想讀每個文件和聯繫號碼每一個到向量。 如果我們假設我有3個文件,我將有3個向量Mj的組件,... 如何在Python中執行此操作?
感謝您的幫助。
我會使用一個正則表達式來走線分開:
import re
lineRE = re.compile(r'''
\#\s*
Mj\s*=\s*(?P<Mj>[-+0-9eE.]+)\s*
ff\s*=\s*(?P<ff>[-+0-9eE.]+)\s*
gg\s*=\s*(?P<gg>[-+0-9eE.]+)
''', re.VERBOSE)
for filename in filenames:
for line in file(filename, 'r'):
m = lineRE.match(line)
if not m:
continue
Mj = m.group('Mj')
ff = m.group('ff')
gg = m.group('gg')
# Put them in whatever lists you want here.
這裏有一個pyparsing的解決方案,可能會更容易比一個正則表達式解決方案來管理:
text = "# Mj = 1.60 ff = 7580.6 gg = 0.8325 "
from pyparsing import Word, nums, Literal
# subexpression for a real number, including conversion to float
realnum = Word(nums+"-+.E").setParseAction(lambda t:float(t[0]))
# overall expression for the full line of data
linepatt = (Literal("#") + "Mj" + "=" + realnum("Mj") +
"ff" + "=" + realnum("ff") +
"gg" + "=" + realnum("gg"))
# use '==' to test for matching line pattern
if text == linepatt:
res = linepatt.parseString(text)
# dump the matched tokens and all named results
print res.dump()
# access the Mj data field
print res.Mj
# use results names with string interpolation to print data fields
print "%(Mj)f %(ff)f %(gg)f" % res
打印:
['#', 'Mj', '=', 1.6000000000000001, 'ff', '=', 7580.6000000000004, 'gg', '=', 0.83250000000000002]
- Mj: 1.6
- ff: 7580.6
- gg: 0.8325
1.6
1.600000 7580.600000 0.832500
有趣。現在嘗試在沒有'from pyparsing import *'的情況下編寫它,[非常不鼓勵](http://docs.python.org/howto/doanddont.html#from-module-import) – 2010-07-06 12:02:39
我也勸阻它(http: //my.safaribooksonline.com/9780596514235/basic_form_of_a_pyparsing_program),但我想我匆匆趕過這些簡單的解析器。 – PaulMcG 2010-07-06 13:10:29
所以矢量Mj =(1.60,7580,0.8325)?我不太清楚你想要什麼,請提供更多細節。 – 2010-07-05 18:30:07