2015-10-05 56 views
-2

我有点失去的那一刻: 我有看这样的行文本文件:Python的循环,从文件的每一行获取数据,并将其转换为十进制

/dev/input/event0: 0003 0035 000002ac 
/dev/input/event0: 0003 0036 000008fb 

有许多像行这一点,我想使脚本,该脚本会从每行的最后一个十六进制值,然后用输出看起来像这样把它们写入文件:

something someting hex_from_line_1 hex_from_line_2 
something someting hex_from_line_3 hex_from_line_4 

等。 因为我是Python的新手,所以在制作循环时会遇到一些麻烦。 你可以给我任何指导吗? (我不是要求整个循环,只是指导 - 我很想学习,不使用一些完成的代码)

+0

添加'确切'简单的输入和输出。避免“东西”像东西 –

+0

提供你已经尝试过的代码和错误 – garg10may

+0

这有点不清楚(所以答案会不同)。对于示例输入,输出行将是什么?我回答假设你真的意味着_last_十六进制值(所以输出将是'000002ac 000008fb'),但标题可能意味着转换为10进制,或者在':'之后使用所有十六进制,而不仅仅是最后一个十六进制的术语等,你可以澄清? – ShadowRanger

回答

2

Python的zip有趣的一点是,它会乐意将相同的迭代器多次作为参数,让您轻松配对输入。例如:

# For efficiency, if you're on Python 2, include this line so zip is a generator that produces pairs on demand, rather than eagerly slurping the whole file 
from future_builtins import zip 

with open('myinput') as f: 
    # Creates a generator that produces only the final space separated value for each line (could be anything; not checking for hex) 
    final_hex = (line.rsplit(None, 1)[-1] for line in f) 
    # By using the same generator twice, we get the 1st, 3rd, 5th, etc. from one 
    # and the 2nd, 4th, 6th, etc. from the other. 
    for hexa, hexb in zip(final_hex, final_hex): 
     print("something something", hexa, hexb) # Python 3 print function 
     print "something something", hexa, hexb # Python 2 print statement 

注意:如果输入的数据是不是偶数行,这将下降最终未成输入。如果你想要不成对的值,你可以使用itertools.zip_longest(Python 2上的izip_longest)。

+0

对不起,提供了“整个循环”,但这是没有一个例子很难解释的事情之一。 – ShadowRanger

+0

此外,您的问题的标题似乎想要转换为十进制;如果是这样的话,你需要将生成器表达式从十六进制改为十进制(转换为实际的'int',因为'print'将会转换回打印):'final_val =(int(line.rsplit(None ,1)[ - 1],16)用于f)中的行。 – ShadowRanger

0

我有点失去的那一刻:我有一个看起来像 行文本文件,它是:/ dev /输入/ EVENT0:0003 0035 000002ac的/ dev /输入/ EVENT0:0003 0036 000008fb有许多这样的行,并且我想让 脚本从每行得到最后一个十六进制值,然后将它们写入 文件中,输出如下所示:something someting hex_from_line_1 hex_from_line_2 something someting hex_from_line_3 hex_from_line_4依此类推。由于我是Python新手,在制作循环时会遇到一些问题 。你能给我任何指导吗? (我不要求对整个循环,唯一的指导 - 我爱学习 的是,不要使用一些完成的代码)的文件中

环比线这样

with open('filename.txt','r') as f: 
    for line in f: 
     hexNibble=line[-1] #this is a string 
     hexValue=int(hexNibble,16) #this is an integer 
     #Now you have the integer value of the last hex nibble on the line 
     #So... 
     #Continue doing whatever you want to do with it... 
0

file.txt的

/dev/input/event0: 0003 0035 000002ac 
/dev/input/event0: 0003 0036 000008fb 
/dev/input/event0: 0003 0035 000002ad 
/dev/input/event0: 0003 0036 000008fe 
/dev/input/event0: 0003 0035 000002af 
/dev/input/event0: 0003 0036 000008fg 
/dev/input/event0: 0003 0036 000008fz 

代码

with open('file.txt', 'rb') as f: 
    data = [x.split(': ')[1].strip() for x in f.read().splitlines()] 

with open('output.txt', 'wb') as f: 
    for i in range(0, len(data), 2): 
     f.write('something something {0}\n'.format(' '.join(data[i:i+2]))) 
相关问题