从txt文件中提取相关数据

时间:2018-11-14 14:17:37

标签: python

如果使用numpy.loadtxt具有某种格式(具有特定间距的列),我知道如何从.txt文件中提取数据,但是我现在面临的问题更加复杂。假设a具有以下格式的数据:

*** model xy ***    
    date: 11.14.18                         gate time: 190 sec
    enviroment Ug=    483 counts        time: 09:19:55
    enviroment Ug=    777 counts        time: 09:21:55
    enviroment Ug=    854 counts        time: 09:53:55
                          .
                          .
                          .

对我来说,相关信息是计数和登门时间。我知道我可以使用open("some txt file", "r")来读取txt文件,但是我不知道如何删除每行的无用信息。

3 个答案:

答案 0 :(得分:1)

您需要逐行阅读txt,您可以为此使用readlines()。对于从第二行开始的每一行,您可以分割字符串

"enviroment Ug=    483 counts        time: 09:19:55".split()

这将导致

['enviroment', 'Ug=', '483', 'counts', 'time:', '09:19:55']

您可以访问[2][-1]元素以获取所需的信息

答案 1 :(得分:1)

为此尝试使用pandas

假设您的文件是第一记录为fixed-width的文件,您可以执行以下操作:

In [1961]: df = pd.read_fwf('t.txt')

In [1962]: df
Out[1962]: 
   date: 11.14.18  Unnamed: 1 Unnamed: 2  gate time: 190  sec
0  enviroment Ug=         483     counts  time: 09:19:55  NaN
1  enviroment Ug=         777     counts  time: 09:21:55  NaN
2  enviroment Ug=         854     counts  time: 09:53:55  NaN

In [1963]: df.columns
Out[1963]: 
Index([u'date: 11.14.18', u'Unnamed: 1', u'Unnamed: 2', u'gate time: 190',
       u'sec'],
      dtype='object')

# the above gives you the column names. 
#You can see in `df` that the counts values  and gate_time values lie in individual columns.

因此,只需从dataframe(df)中提取这些列:

In [1967]: df[['Unnamed: 1', 'gate time: 190']]
Out[1967]: 
   Unnamed: 1  gate time: 190
0         483  time: 09:19:55
1         777  time: 09:21:55
2         854  time: 09:53:55

现在,您可以将以上内容写在csv文件中。

In [1968]: df.to_csv('/home/mayankp/Desktop/tt.csv', header=False, index=False, columns=['Unnamed: 1', 'gate time: 190'])

这种方法基本上使您不必使用for循环和复杂的正则表达式。

答案 2 :(得分:1)

您可以轻松地一次读取文件中的所有文本,并使用正则表达式查找所需的数据:

import re
with open("some txt file", "r") as fin:
    all_text = fin.read()

    # Find the gate time
    gate_time_r = re.compile(r'gate\s+time:\s+(\d+)', re.IGNORECASE)
    gate_time = int(gate_time_r.search(all_text).groups()[0])

    # Find the counts
    counts_r = re.compile(r'enviroment\s+ug=\s+(\d+)', re.IGNORECASE)
    counts_list = list(map(int, counts_r.findall(all_text)))

门时间正则表达式:gate\s+time:\s+(\d+)仅匹配在字符串gate time:之后出现数字的模式,并匹配组中的该数字。您只需使用gate_time_r.search(all_text)运行此正则表达式,它将找到一个匹配项,然后可以选择其第一组。

计算正则表达式:enviroment\s+ug=\s+(\d+)。它匹配一种模式,即tehre在enciroment ug=之后是一个数字,并在组中选择该数字。

由于all_text字符串中有多个匹配项,因此您可以使用findall搜索所有匹配项。

它将返回正则表达式中存在的组的列表,因此它将是实际计数的列表。只需将其转换为int即可。

相关问题