Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—从文件中的每一行提取特定的数字_Python_String - Fatal编程技术网

Python—从文件中的每一行提取特定的数字

Python—从文件中的每一行提取特定的数字,python,string,Python,String,我有一个文本文件,它有1000行文本,但我感兴趣的是在大文本文件中只找到某些行,并从这些行中提取一些有趣的数字。下面是示例文本文件- [Some text] [Some text] ...... 01/12/14 17:19:01.942 DEBUG [MaccParamsProducts-5] Get location (x,y,z,storeid,bustLeard,confidence): (50.0,41.153217,0.0,215,9,194.0) ...... [Some text

我有一个文本文件,它有1000行文本,但我感兴趣的是在大文本文件中只找到某些行,并从这些行中提取一些有趣的数字。下面是示例文本文件-

[Some text]
[Some text]
......
01/12/14 17:19:01.942 DEBUG [MaccParamsProducts-5] Get location (x,y,z,storeid,bustLeard,confidence): (50.0,41.153217,0.0,215,9,194.0)
......
[Some text]
[Some text]
......
01/18/14 17:29:54.852 DEBUG [MaccParamsProducts-2] Get location (x,y,z,storeid,bustLeard,confidence): (60.0,51.253947,0.0,125,10,194.0)
现在,我只想获取包含字符串“Get location”的行。 一旦我得到那条线,我只想得到x和y坐标值。例如,在上面的Get位置行中,我只想得到60.0和51.253947。我的最终输出应该只有这两个值

到目前为止,我已经能够得到行,但没有得到值,因为我对python非常陌生。下面是我的代码片段-

import sys
with open("test.log", "r") as input_file:
     with open('res4.txt', 'w') as output_file:
                output_file.write("Lines containing x-y co-ordinates\n")
                for line in input_file:
                        if "Get location" in line:
                                output_file.write(line)
如果有人能告诉我如何提取这两个值并将其输出到一个新的文本文件中,那就太好了!感谢您的任何帮助

with open("test.txt") as f:
    for line in f:
        if "Get location" in line:
            data = line.rsplit(None,1)[1]
            print(data.strip("()").split(",", 2)[:2])
输出:

['50.0', '41.153217']
['60.0', '51.253947']
要将其写入文件,只需打开另一个文件,然后边写边写:

import csv
with open("test.txt") as f,open("out.txt","w")as out:
    wr = csv.writer(out)
    for line in f:
        if "Get location" in line:
            data = line.rsplit(None,1)[1]
            wr.writerow(data.strip("()", 2).split(",")[:2])
out.txt:

50.0,41.153217
60.0,51.253947
line.rsplit(None,1)[1]
从末尾开始拆分一次空格,我们剥离
()
并拆分
得到前两个数字

或使用file.write和unpack:

with open("test.txt") as f,open("out.txt","w") as out:
    for line in f:
        if "Get location" in line:
            a,b,_ = line.rsplit(None,1)[1].strip("()").split(",", 2)
            out.write("{},{}\n".format(a,b))

Python是必要的吗?这是Shell工具的完美工作:

grep 'Get location' | sed 's/.*: (\([^,]*\),\([^,]*\),.*/\1, \2/'

@用户3044621,没问题,不客气。您也可以使用正则表达式,但不确定它是否更有效。